package cn.xspace.wnx.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import android.util.Log;

import com.xspace.android.xafcommon.appliction.BaseApplication;
import com.xspace.android.xafcommon.util.LogUtil;
import com.xspace.android.xafcommon.util.PageUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xspace.chatui.bean.ChatFileEntity;
import cn.xspace.chatui.bean.MessageEntity;
import cn.xspace.chatui.bean.MsgRecordEntity;
import cn.xspace.library.bean.OrgDeptUserBean;
import cn.xspace.library.bean.Type;
import cn.xspace.library.util.ContentType;
import cn.xspace.library.util.MsgType;
import cn.xspace.library.util.MyInfoUtil;
import cn.xspace.wnx.entity.NewFriendBean;
import cn.xspace.wnx.entity.WNXBean;

/**
 * Created by liuchen on 2016/10/11.
 */

public class WNXDBManager {
    static private volatile WNXDBManager dbMgr = null;
    private WNXDBHelper dbHelper;
    private static final String TAG = "WNXDBManager";

    private WNXDBManager() {
        dbHelper = WNXDBHelper.getInstance(BaseApplication.mInstance);
    }
//    public  static

    synchronized public static WNXDBManager getInstance() {

        WNXDBManager inst = dbMgr;
        if (inst == null) {
            synchronized (WNXDBManager.class) {
                inst = dbMgr;
                if (inst == null) {
                    inst = new WNXDBManager();
                    dbMgr = inst;
                }
            }
        }
        return inst;
    }

    /**
     * 构建 全部ContentValues
     *
     * @param entity
     */
    private ContentValues buildAllContentValue(MessageEntity entity) {
        ContentValues values = new ContentValues();
        values.put(MessageRecordDao.COLUMN_MSG_TYPE, entity.msg_type);
        values.put(MessageRecordDao.COLUMN_MSG_LOGO, entity.msg_logo);
        values.put(MessageRecordDao.COLUMN_MSG_SENDER_ID, entity.msg_sender_id);
        values.put(MessageRecordDao.COLUMN_MSG_SENDER_NAME, entity.msg_sender_name);
        values.put(MessageRecordDao.COLUMN_MSG_RECEIVER_ID, entity.msg_receiver_id);
        values.put(MessageRecordDao.COLUMN_MSG_RECEIVER_NAME, entity.msg_receiver_name);
        values.put(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT, entity.msg_unread_count);
        values.put(MessageRecordDao.COLUMN_MSG_WARN_STATUS, entity.msg_warn_status);
        values.put(MessageRecordDao.COLUMN_MSG_LAST_TIME, entity.msg_last_time);
        values.put(MessageRecordDao.COLUMN_MSG_CONTENT_TYPE, entity.msg_content_type);
        values.put(MessageRecordDao.COLUMN_MSG_IS_SHOW, entity.isShow);
        values.put(MessageRecordDao.COLUMN_MSG_CONTENT, entity.msg_content);
        values.put(MessageRecordDao.COLUMN_MSG_SEND_STATUS, entity.msg_send_status);
        values.put(MessageRecordDao.COLUMN_MSG_GROUP_ID, entity.msg_group_id);
        values.put(MessageRecordDao.COLUMN_MSG_GROUP_NAME, entity.msg_group_name);
        values.put(MessageRecordDao.COLUMN_MSG_GROUP_TYPE, entity.group_type);
        values.put(MessageRecordDao.COLUMN_USER_SEX, entity.user_sex);
        values.put(MessageRecordDao.COLUMN_MSG_GROUP_MEMBER, entity.group_member);
        values.put(MessageRecordDao.COLUMN_MSG_INDEX, entity.msg_index);
        values.put(MessageRecordDao.COLUMN_TIME_STAMP, System.currentTimeMillis());
        return values;
    }

    /**
     * 更新消息列表
     *
     * @param entity
     */
    synchronized public void saveOrUpdateMessageList(MessageEntity entity) {
        if (entity == null)
            return;
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        if (entity.msg_type == MsgType.NOTICE.toNumber()) {
            insertOrUpdateNotice(entity);
        } else if (entity.msg_type == MsgType.WNX_MSG.toNumber()) {
            //w微农信信息
            insertOrUpdateWNX(entity);
        } else if (entity.msg_type == MsgType.CHAT_SINGLE.toNumber()) {
            Log.d(TAG, "222");
            //单聊
            insertOrUpdateChatSingle(sqlDb, entity);
        } else if (entity.msg_type == MsgType.CHAT_CROUP.toNumber()) {
            //群聊
            insertOrUpdateChatGroup(entity);
        } else {
            //拓展
            Log.d(TAG, "4444");
        }
    }

    public synchronized void savePreferences(String key, String value) {
        String selection = PreferencesDb.key + "= ? ";
        String[] selectionArgs = new String[]{key};
        ContentValues values = new ContentValues();
        values.put(PreferencesDb.key, key);
        values.put(PreferencesDb.value, value);
        Cursor cur = null;
        try {
            SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
            cur = sqlDb.query(PreferencesDb.TABLE_NAME, null, selection, selectionArgs, null, null, null);
            if (cur != null && cur.getCount() > 0) {
                // 存在对应key更新
                int result = sqlDb.update(PreferencesDb.TABLE_NAME, values, selection, selectionArgs);
                LogUtil.d("update result " + result);
            } else {
                long insertResult = sqlDb.insert(PreferencesDb.TABLE_NAME, null, values);
                LogUtil.d("insert result " + insertResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeDbAndCursor(cur);
        }
    }

    public synchronized String queryPreferences(String key) {
        String selection = PreferencesDb.key + "=?";
        String[] selectionArgs = new String[]{key};
        // LogUtil.d("keyName=="+key);
        String value = "";
        Cursor cur = null;
        try {
            // db.open();
            String[] columns = {PreferencesDb.key, PreferencesDb.value};
            SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
            cur = sqlDb.query(PreferencesDb.TABLE_NAME, columns, selection, selectionArgs, null, null, null);
            // LogUtil.d("cur=="+cur.getCount());
            if (cur != null) {
                for (int i = 0; i < cur.getCount(); i++) {
                    if (cur.moveToPosition(i)) {
                        value = cur.getString(1);
                        // LogUtil.d("cur value=="+value);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cur != null) {
                try {
                    cur.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
        }
        return value;
    }

    /**
     * 插入或者修改微农信
     *
     * @param entity
     */
    private void insertOrUpdateWNX(MessageEntity entity) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        if (isExsitMotice(sqlDb, entity.msg_type)) {
            //存在,需要更新时间，内容，logo，name，未读数量
            ContentValues updateValues = new ContentValues();
            if (entity.isRead) {
                //已读，不操作
            } else {
                //未读，更新数量
                int count = otherMap.get(entity.msg_type);
                LogUtil.e("接收到微农信推送之前的未读数量：" + count);
                count++;
                LogUtil.e("接收到微农信推送之后的未读数量：" + count);
                updateValues.put(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT, count);
            }
            updateValues.put(MessageRecordDao.COLUMN_MSG_LAST_TIME, entity.msg_last_time);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT_TYPE, entity.msg_content_type);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT, entity.msg_content);
            updateValues.put(MessageRecordDao.COLUMN_MSG_LOGO, entity.msg_logo);
            updateValues.put(MessageRecordDao.COLUMN_MSG_SENDER_NAME, entity.msg_sender_name);
            String whereArgs = MessageRecordDao.COLUMN_MSG_TYPE + "= ? ";
            String[] args = new String[]{entity.msg_type + ""};
            int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, whereArgs, args);
            LogUtil.d(String.format("更新微农信 SenderName 为 %s的记录，结果为%d", entity.msg_sender_name, result));
        } else {
            //不存在此条单聊
            //不存在此条通知
            if (entity.isRead) {
                //已读，不操作
            } else {
                //未读，更新数量
                entity.msg_unread_count = 1;
            }
            ContentValues inserValues = buildAllContentValue(entity);
            long result = sqlDb.insert(MessageRecordDao.TABLE_NAME, null, inserValues);
            LogUtil.d(String.format("插入单聊 SenderName 为 %s的记录，结果为%d", entity.msg_sender_name, result));
        }
    }

//    /**
//     * 保存微农信机构列表 // TODO 放弃
//     *
//     * @param beanList
//     */
//    public synchronized void saveWNXList(ArrayList<WNXBean> beanList) {
//        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
//        for (WNXBean bean : beanList) {
//            if (isExistWNXDep(sqlDb, bean.msg_sender_id)) { //列表中是否存在该机构id
//                //不做处理
//            } else {
//                //添加
//                ContentValues insetValues = new ContentValues();
//                insetValues.put(MessageRecordDao.COLUMN_MSG_SENDER_NAME, bean.msg_sender_name);
//                insetValues.put(MessageRecordDao.COLUMN_MSG_TYPE, MessageEntity.MsgType.WNX_MSG.toNumber());
//                insetValues.put(MessageRecordDao.COLUMN_MSG_SENDER_ID, bean.msg_sender_id);
//                insetValues.put(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT, 0);
//                long result = sqlDb.insert(MessageRecordDao.TABLE_NAME, null, insetValues);
//                LogUtil.d(String.format("存入机构为%s的记录，结果为%d", bean.msg_sender_name, result));
//            }
//        }
//    }

    /**
     * 将获取到的微农信机构列表保存,bean类型保存为1
     *
     * @param beanList
     */
    public synchronized void saveWNXOrgList(ArrayList<WNXBean> beanList) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        for (WNXBean wnxBean : beanList) {
            if (TextUtils.isEmpty(wnxBean.inserttime)) {
                wnxBean.inserttime = System.currentTimeMillis() + "";
            }
            ContentValues contentValues = new ContentValues();
            contentValues.put(NoticeDao.COLUMN_MSG_SENDER_ID, wnxBean.msg_sender_id);
            contentValues.put(NoticeDao.COLUMN_MSG_SENDER_NAME, wnxBean.msg_sender_name);
            contentValues.put(NoticeDao.COLUMN_MSG_UNREAD_FLAG, "1"); //已读

            contentValues.put(NoticeDao.COLUMN_TIME_STAMP, wnxBean.inserttime);
            contentValues.put(NoticeDao.COLUMN_MSG_CONTENT, wnxBean.content);
            contentValues.put(NoticeDao.COLUMN_MSG_ID, wnxBean.msg_id);
            contentValues.put(NoticeDao.COLUMN_MSG_CONTENT_TYPE, wnxBean.msg_content_type);
            contentValues.put(NoticeDao.COLUMN_MSG_KIND, wnxBean.msg_kind);
            contentValues.put(NoticeDao.COLUMN_MSG_LOGO, wnxBean.msg_logo);
            contentValues.put(NoticeDao.COLUMN_MSG_SEND_TIME, wnxBean.msg_send_time);
            contentValues.put(NoticeDao.COLUMN_MSG_TITLE, wnxBean.msg_title);
            contentValues.put(NoticeDao.COLUMN_MSG_TYPE, wnxBean.msg_type);
            contentValues.put(NoticeDao.COLUMN_REMARK3, 1); //bean类型为1,表示只是列表展示用,非其他所用
            long resut = sqlDb.insert(NoticeDao.TABLE_NAME, null, contentValues);
            LogUtil.d(TAG, String.format("插入微农信表 发送人名字为 %s ，结果为%d", wnxBean.msg_sender_name, resut));
        }
    }

    /**
     * 表中是否存在该记录
     *
     * @param sqlDb
     * @param dept_id
     * @return
     */
    private boolean isExistWNXDep(SQLiteDatabase sqlDb, String dept_id) {
        Cursor cursor = sqlDb.rawQuery("select  " + MessageRecordDao.COLUMN_MSG_SENDER_ID + " from " +
                        MessageRecordDao.TABLE_NAME + " where " +
                        MessageRecordDao.COLUMN_MSG_TYPE + " = " +
                        MsgType.WNX_MSG.toNumber() + " AND " +
                        MessageRecordDao.COLUMN_MSG_SENDER_ID + " = '"
                        + dept_id + "'",
                null);
        if (cursor.moveToFirst()) {
//            int count = cursor.getInt(1);
//            otherMap.put(type, count);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 插入或者修改公告
     *
     * @param entity
     */
    synchronized public void insertOrUpdateNotice(MessageEntity entity) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        if (isExsitMotice(sqlDb, entity.msg_type)) {
            //存在,需要更新时间，内容，logo，name，未读数量
            ContentValues updateValues = new ContentValues();
            if (entity.isRead) {
                //已读，不操作
            } else {
                //未读，更新数量
                int count = otherMap.get(entity.msg_type);
                LogUtil.e("接收到公告推送之前的未读数量：" + count);
                count++;
                LogUtil.e("接收到公告推送之后的未读数量：" + count);
                updateValues.put(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT, count);
            }
            updateValues.put(MessageRecordDao.COLUMN_MSG_LAST_TIME, entity.msg_last_time);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT_TYPE, entity.msg_content_type);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT, entity.msg_content);

            if (!TextUtils.isEmpty(entity.msg_logo)) {
                updateValues.put(MessageRecordDao.COLUMN_MSG_LOGO, entity.msg_logo);
            }
            updateValues.put(MessageRecordDao.COLUMN_MSG_SENDER_NAME, entity.msg_sender_name);
            String whereArgs = MessageRecordDao.COLUMN_MSG_TYPE + "= ? ";
            String[] args = new String[]{entity.msg_type + ""};
            int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, whereArgs, args);
            LogUtil.d(String.format("更新单聊 SenderName 为 %s的记录，结果为%d", entity.msg_sender_name, result));
        } else {
            //不存在此条通知
            if (entity.isRead) {
                //已读，不操作
            } else {
                //未读，更新数量
                entity.msg_unread_count = 1;
            }
            ContentValues inserValues = buildAllContentValue(entity);
            long result = sqlDb.insert(MessageRecordDao.TABLE_NAME, null, inserValues);
            LogUtil.d(String.format("插入单聊 SenderName 为 %s的记录，结果为%d", entity.msg_sender_name, result));
        }
    }

    /**
     * 插入或者修改公告,读了之后减一
     *
     * @param entity
     */
    synchronized public void insertOrUpdateNoticeReduce(MessageEntity entity) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        if (isExsitMotice(sqlDb, entity.msg_type)) {
            //存在,需要更新时间，内容，logo，name，未读数量
            ContentValues updateValues = new ContentValues();
            if (entity.isRead) {
                //已读，不操作
            } else {
                //未读，更新数量
                int count = otherMap.get(entity.msg_type);
                LogUtil.e("读公告之前的未读数量：" + count);
                if (count > 0) {
                    count--;
                }
                LogUtil.e("读公告之后的未读数量：" + count);
                updateValues.put(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT, count);
            }
            updateValues.put(MessageRecordDao.COLUMN_MSG_LAST_TIME, entity.msg_last_time);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT_TYPE, entity.msg_content_type);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT, entity.msg_content);
            updateValues.put(MessageRecordDao.COLUMN_MSG_LOGO, entity.msg_logo);
            updateValues.put(MessageRecordDao.COLUMN_MSG_SENDER_NAME, entity.msg_sender_name);
            String whereArgs = MessageRecordDao.COLUMN_MSG_TYPE + "= ? ";
            String[] args = new String[]{entity.msg_type + ""};
            int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, whereArgs, args);
            LogUtil.d(String.format("更新单聊 SenderName 为 %s的记录，结果为%d", entity.msg_sender_name, result));
        } else {
            //不存在此条单聊
            ContentValues inserValues = buildAllContentValue(entity);
            long result = sqlDb.insert(MessageRecordDao.TABLE_NAME, null, inserValues);
            LogUtil.d(String.format("插入单聊 SenderName 为 %s的记录，结果为%d", entity.msg_sender_name, result));
        }
    }

    /**
     * 更新消息列表中的通知公告数据,通过查询通知公告中最新的一条数据
     */
    public MessageEntity updateMessageListNoticeContent() {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        MessageEntity bean = null;
        String newsSql = " select * from " + NoticeDao.TABLE_NAME + " where  " +
                NoticeDao.COLUMN_MSG_TYPE + " = " + MsgType.NOTICE.toNumber() + " order by " +
                NoticeDao.COLUMN_MSG_SEND_TIME + " DESC";
        LogUtil.d(TAG, "wubaojie>>>updateMessageListNoticeContent: sql : " + newsSql);
        Cursor newsCur = sqlDb.rawQuery(newsSql, null);
        if (newsCur.moveToNext()) {
            bean = buildNoticeByCursor(newsCur);
            bean.isCanSlide = false;
            bean.msg_type = MsgType.NOTICE.toNumber();
        }
        try {
            newsCur.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    /**
     * 更新消息列表中的微农信数据,通过查询微农信中最新的一条数据
     */
    public MessageEntity updateMessageListWNXContent() {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        MessageEntity bean = null;
        String newsSql = " select * from " + NoticeDao.TABLE_NAME + " where  " +
                NoticeDao.COLUMN_MSG_TYPE + " = " + MsgType.WNX_MSG.toNumber() + " and " +
                NoticeDao.COLUMN_REMARK3 + " <> 1 order by " +
                NoticeDao.COLUMN_MSG_SEND_TIME + " DESC";
        LogUtil.d(TAG, "wubaojie>>>updateMessageListWNXContent: sql : " + newsSql);
        Cursor newsCur = sqlDb.rawQuery(newsSql, null);
        if (newsCur.moveToNext()) {
            bean = buildNoticeByCursor(newsCur);
            bean.isCanSlide = false;
            bean.msg_type = MsgType.WNX_MSG.toNumber();
            LogUtil.d(TAG, "wubaojie>>>updateMessageListWNXContent: bean:" + bean.toString());
        }
        try {
            newsCur.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    /**
     * 更新消息列表中的群助手数据,通过查询群助手中最新的一条数据
     */
    public MessageEntity updateMessageListGroupContent() {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        MessageEntity bean = null;

//        String newsSql = "select * from " + ChatRecordDao.TABLE_NAME + " where " +
//                ChatRecordDao.COLUMN_MSG_GROUP_ID + " = (select " +
//                MessageRecordDao.COLUMN_MSG_GROUP_ID + " from " +
//                MessageRecordDao.TABLE_NAME + " where " +
//                MessageRecordDao.COLUMN_MSG_TYPE + " = " +
//                MessageEntity.MsgType.CHAT_CROUP.toNumber() + " order by " +
//                MessageRecordDao.COLUMN_MSG_LAST_TIME + " desc limit 0,1) and " +
//                ChatRecordDao.COLUMN_MSG_TYPE + " = " +
//                MessageEntity.MsgType.CHAT_CROUP.toNumber() + " and " +
//                ChatRecordDao.COLUMN_IS_SENDER_MINE + " <> 1 order by " +
//                ChatRecordDao.COLUMN_MSG_SEND_TIME + " desc";
//        String sql2 = "select t_chat_record.* " +
//                "from  t_chat_record ,t_messagelist " +
//                "where t_chat_record.msg_group_id=t_messagelist.msg_group_id " +
//                "and t_chat_record.msg_type=3 and t_chat_record.is_sender_mine<>1 " +
//                "and t_messagelist.msg_type=3 " +
//                "order by t_chat_record.time desc";
        //首先查询消息列表中消息类型为群组,并且提醒打开的群组id,按照时间降序
        String findNewsGroup = "SELECT * FROM " + MessageRecordDao.TABLE_NAME + " WHERE " +
                MessageRecordDao.COLUMN_MSG_TYPE + " = " +
                MsgType.CHAT_CROUP.toNumber() + " AND " +
                MessageRecordDao.COLUMN_MSG_GROUP_TYPE + " <> " + Type.GroupType.TEMP_GROUP + " AND " +
                MessageRecordDao.COLUMN_MSG_WARN_STATUS + " = " +
                MessageEntity.WarnStatus.WARN.toNumber() + " ORDER BY " +
                MessageRecordDao.COLUMN_MSG_LAST_TIME + " DESC";
        LogUtil.d(TAG, "wubaojie>>>updateMessageListGroupContent: findNewsGroup : " + findNewsGroup);
        Cursor newsCur = sqlDb.rawQuery(findNewsGroup, null);
        while (newsCur.moveToNext()) { //遍历获取群组id,去另一张表查询最新的并且不是自己发的消息
//            bean = buildGroupByCursor(newsCur);
//            LogUtil.d(TAG, "wubaojie>>>updateMessageListGroupContent: bean:" + bean.toString());
            String groupId = newsCur.getString(newsCur.getColumnIndex(MessageRecordDao.COLUMN_MSG_GROUP_ID));
            String findNewsMsg = "SELECT * FROM " + ChatRecordDao.TABLE_NAME + " WHERE " +
                    ChatRecordDao.COLUMN_MSG_GROUP_ID + " = '" + groupId + "' AND " +
                    ChatRecordDao.COLUMN_MSG_TYPE + " = " +
                    MsgType.CHAT_CROUP.toNumber() + " AND " +
                    ChatRecordDao.COLUMN_IS_SENDER_MINE + " <> 1 ORDER BY " +
                    ChatRecordDao.COLUMN_MSG_SEND_TIME + " DESC";
            LogUtil.d(TAG, "wubaojie>>>updateMessageListGroupContent: findNewsMsg:" + findNewsMsg);
            Cursor msgCursor = sqlDb.rawQuery(findNewsMsg, null);
            if (msgCursor.moveToNext()) {
                bean = new MessageEntity();
                bean.msg_last_time = newsCur.getString(newsCur.getColumnIndex(MessageRecordDao.COLUMN_MSG_LAST_TIME));
                String groupName = newsCur.getString(newsCur.getColumnIndex(MessageRecordDao.COLUMN_MSG_GROUP_NAME));
                bean.msg_group_id = newsCur.getString(newsCur.getColumnIndex(MessageRecordDao.COLUMN_MSG_GROUP_ID));
                bean.msg_content = String.format("%s群收到一条新消息", TextUtils.isEmpty(groupName) ? "未命名" : groupName);
                bean.isCanSlide = false;
                bean.msg_type = MsgType.CHAT_CROUP.toNumber();
                bean.group_type = Type.GroupType.MANAGER;
                LogUtil.d(TAG, "wubaojie>>>updateMessageListGroupContent: bean:" + bean.toString());
                closeDbAndCursor(msgCursor);
                break; //如果找到了最新的消息就退出循环,没找到就再找消息列表中最新的会话中的最新的接受到的消息
            }
        }
        closeDbAndCursor(newsCur);
        return bean;
    }

    /**
     * 创建一个MessageEntity,置顶显示时使用
     *
     * @param cursor
     * @return
     */
    private MessageEntity buildNoticeByCursor(Cursor cursor) {
        MessageEntity bean = new MessageEntity();
        bean.msg_last_time = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_SEND_TIME));
        String msg_sender_name = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_SENDER_NAME));
        String msg_title = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_TITLE));
        bean.msg_content = String.format("%s : %s", msg_sender_name, msg_title);
        return bean;
    }

    /**
     * 创建一个MessageEntity,置顶显示时使用
     *
     * @param cursor
     * @return
     */
    private MessageEntity buildGroupByCursor(Cursor cursor) {
        MessageEntity bean = new MessageEntity();
//        bean.msg_last_time = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_LAST_TIME));
//        String groupName = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_GROUP_NAME));
        bean.msg_last_time = cursor.getString(cursor.getColumnIndex(ChatRecordDao.COLUMN_MSG_SEND_TIME));
        String groupName = cursor.getString(cursor.getColumnIndex(ChatRecordDao.COLUMN_MSG_GROUP_NAME));
        bean.msg_group_id = cursor.getString(cursor.getColumnIndex(ChatRecordDao.COLUMN_MSG_GROUP_ID));
        bean.msg_content = String.format("%s群收到一条新消息", TextUtils.isEmpty(groupName) ? "未命名" : groupName);
        bean.isCanSlide = false;
        bean.msg_type = MsgType.CHAT_CROUP.toNumber();
        return bean;
    }

    /**
     * 清除消息列表 对应的content
     *
     * @param id
     * @param chatType
     * @return
     */
    public int clearMessageRecord(String id, int chatType) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues cb = new ContentValues();
        cb.put(MessageRecordDao.COLUMN_MSG_CONTENT, "");
        int result = sqlDb.update(MessageRecordDao.TABLE_NAME, cb,
                (chatType == MsgType.CHAT_CROUP.toNumber()
                        ? MessageRecordDao.COLUMN_MSG_GROUP_ID : MessageRecordDao.COLUMN_MSG_SENDER_ID) + " = ?"
                , new String[]{id});
        LogUtil.d(" 删除聊天消息  result >>" + result + " id " + id + " chatType " + chatType);
        return result;
    }

    public int updateGroupType(MessageEntity entity) {
        if (entity == null)
            return 0;
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues updateValues = new ContentValues();
        updateValues.put(MessageRecordDao.COLUMN_MSG_GROUP_TYPE, entity.group_type);
        String whereArgs = MessageRecordDao.COLUMN_MSG_GROUP_ID + "= ? ";
        String[] args = new String[]{entity.msg_group_id};
        int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, whereArgs, args);
        LogUtil.d(TAG, String.format("更新群聊 群组id 为 %s的记录，结果为%d", entity.msg_group_id, result));
        return result;
    }

    /**
     * 插入或者修改单聊
     *
     * @param entity
     */
    public synchronized void insertOrUpdateChatSingle(SQLiteDatabase sqlDb, MessageEntity entity) {
        Log.d(TAG, "111");
        LogUtil.d(TAG, "insertOrUpdateChatSingle  ");
        if (isExsitSingleChat(sqlDb, entity.msg_sender_id)) {
            //存在某条单聊,需要更新时间，内容，logo，name，
            ContentValues updateValues = new ContentValues();
            LogUtil.d(TAG, "MessageEntity  " + entity.toString());
            if (entity.isRead) {
                //已读，不操作
            } else {
                //未读，更新数量
                int count = singleMap.get(entity.msg_sender_id);
                LogUtil.d(TAG, "singleMap coount " + count + " singleMap" + singleMap.toString());
                count++;
                updateValues.put(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT, count);
            }
            updateValues.put(MessageRecordDao.COLUMN_MSG_LAST_TIME, entity.msg_last_time);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT_TYPE, entity.msg_content_type);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT, entity.msg_content);
            updateValues.put(MessageRecordDao.COLUMN_MSG_IS_SHOW, entity.isShow);
            if (!TextUtils.isEmpty(entity.msg_logo)) {
                updateValues.put(MessageRecordDao.COLUMN_MSG_LOGO, entity.msg_logo);
            }
            if (!TextUtils.isEmpty(entity.msg_sender_name)) {
                updateValues.put(MessageRecordDao.COLUMN_MSG_SENDER_NAME, entity.msg_sender_name);
            }
            if (!TextUtils.isEmpty(entity.user_sex)) {
                updateValues.put(MessageRecordDao.COLUMN_USER_SEX, entity.user_sex);
            }
            String whereArgs = MessageRecordDao.COLUMN_MSG_SENDER_ID + "= ? and  " + MessageRecordDao.COLUMN_MSG_TYPE
                    + " = ?";
            String[] args = new String[]{entity.msg_sender_id, entity.msg_type + ""};
            int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, whereArgs, args);
            Log.d(TAG, "222");
            LogUtil.d(TAG, String.format("更新单聊 SenderName 为 %s的记录，结果为%d", entity.msg_sender_name, result));
        } else {
            //不存在此条单聊
            if (entity.isRead) {
                //已读，不操作
            } else {
                //未读，更新数量
                entity.msg_unread_count = 1;
            }
            ContentValues inserValues = buildAllContentValue(entity);
            long result = sqlDb.insert(MessageRecordDao.TABLE_NAME, null, inserValues);
            LogUtil.d(String.format("插入单聊 SenderName 为 %s的记录，结果为%d", entity.msg_sender_name, result));
        }
    }

    /**
     * 插入或者更新群组聊天
     *
     * @param entity
     */
    synchronized public void insertOrUpdateChatGroup(MessageEntity entity) {
        LogUtil.d(TAG, "insertOrUpdateChatGroup");
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        if (isExsitGroupChat(sqlDb, entity.msg_group_id)) {
            //存在某条群聊,需要更新时间，内容，logo，name，发送者id,发送者name,群组名称,群组类型
            ContentValues updateValues = new ContentValues();
            if (entity.isRead) {
                //已读，不操作
            } else {
                //未读，更新数量
                int count = groupMap.get(entity.msg_group_id);
                count++;
                updateValues.put(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT, count);
            }
            updateValues.put(MessageRecordDao.COLUMN_MSG_LAST_TIME, entity.msg_last_time);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT_TYPE, entity.msg_content_type);
            updateValues.put(MessageRecordDao.COLUMN_MSG_CONTENT, entity.msg_content);
            updateValues.put(MessageRecordDao.COLUMN_MSG_IS_SHOW, entity.isShow);
            updateValues.put(MessageRecordDao.COLUMN_MSG_GROUP_TYPE, entity.group_type);

            if (!TextUtils.isEmpty(entity.msg_logo)) {
                updateValues.put(MessageRecordDao.COLUMN_MSG_LOGO, entity.msg_logo);
            }
            if (!TextUtils.isEmpty(entity.msg_sender_name)) {
                updateValues.put(MessageRecordDao.COLUMN_MSG_SENDER_NAME, entity.msg_sender_name);
            }
            if (!TextUtils.isEmpty(entity.msg_sender_id)) {
                updateValues.put(MessageRecordDao.COLUMN_MSG_SENDER_ID, entity.msg_sender_id);
            }
            if (!TextUtils.isEmpty(entity.msg_group_name)) {
                updateValues.put(MessageRecordDao.COLUMN_MSG_GROUP_NAME, entity.msg_group_name);
            }
            if (!TextUtils.isEmpty(entity.user_sex)) {
                updateValues.put(MessageRecordDao.COLUMN_USER_SEX, entity.user_sex);
            }
            if (entity.group_member != 0) {
                updateValues.put(MessageRecordDao.COLUMN_MSG_GROUP_MEMBER, entity.group_member);
            }
            String whereArgs = MessageRecordDao.COLUMN_MSG_GROUP_ID + "= ? ";
            String[] args = new String[]{entity.msg_group_id};
            LogUtil.d(TAG, updateValues.toString());
            int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, whereArgs, args);
            LogUtil.d(TAG, String.format("更新群聊 群组id 为 %s的记录，结果为%d", entity.msg_group_id, result));
        } else {
            //不存在此条群聊
            if (entity.isRead) {
                //已读，不操作
            } else {
                //未读，更新数量
                entity.msg_unread_count = 1;
            }
            ContentValues inserValues = buildAllContentValue(entity);
            long result = sqlDb.insert(MessageRecordDao.TABLE_NAME, null, inserValues);
            LogUtil.d(String.format("插入群聊 群组名称 为 %s的记录，结果为%d", entity.msg_group_name, result));
        }
    }

    /**
     * 判断是否存在某条单聊记录信息
     *
     * @param sqlDb
     * @param sendId
     * @return
     */
    synchronized private boolean isExsitSingleChat(SQLiteDatabase sqlDb, String sendId) {
        LogUtil.d(TAG, "isExsitSingleChat  ");
        String sql = "select  " + MessageRecordDao.COLUMN_TIME_STAMP + " , " +
                MessageRecordDao.COLUMN_MSG_UNREAD_COUNT + " from " + MessageRecordDao.TABLE_NAME + " where " +
                MessageRecordDao.COLUMN_MSG_SENDER_ID + " = '" + sendId + "' AND " + MessageRecordDao.COLUMN_MSG_TYPE
                + " = " + MsgType.CHAT_SINGLE.toNumber();
        LogUtil.d(TAG, "sql " + sql);
        Cursor cursor = sqlDb.rawQuery(sql, null);
        if (cursor.moveToFirst()) {
            int count = cursor.getInt(1);
            singleMap.put(sendId, count);
            LogUtil.d(TAG, "1  count >>" + count);
            return true;
        } else {
            LogUtil.d(TAG, "0");
            return false;

        }
    }


    /**
     * 判断是否存在某条群组聊天
     *
     * @param sqlDb
     * @param groupId
     * @return
     */
    synchronized private boolean isExsitGroupChat(SQLiteDatabase sqlDb, String groupId) {
        Cursor cursor = sqlDb.rawQuery("select  " + MessageRecordDao.COLUMN_TIME_STAMP + " , " + MessageRecordDao
                .COLUMN_MSG_UNREAD_COUNT +
                " from " + MessageRecordDao.TABLE_NAME + " where " + MessageRecordDao.COLUMN_MSG_GROUP_ID + " = '" +
                groupId + "'", null);
        if (cursor.moveToFirst()) {
            int count = cursor.getInt(1);
            groupMap.put(groupId, count);
            return true;
        } else {
            return false;
        }
    }

    private Map<String, Integer> singleMap = new HashMap<>();
    private Map<String, Integer> groupMap = new HashMap<>();
    private Map<Integer, Integer> otherMap = new HashMap<>();

    /**
     * 判断是否有公告或者微农信信息
     *
     * @param sqlDb
     * @param type
     */
    synchronized private boolean isExsitMotice(SQLiteDatabase sqlDb, int type) {
        Cursor cursor = sqlDb.rawQuery("select  " + MessageRecordDao.COLUMN_TIME_STAMP + " , " + MessageRecordDao
                        .COLUMN_MSG_UNREAD_COUNT +
                        " from " + MessageRecordDao.TABLE_NAME + " where " + MessageRecordDao.COLUMN_MSG_TYPE + " = "
                        + type,
                null);
        if (cursor.moveToFirst()) {
            int count = cursor.getInt(1);
            otherMap.put(type, count);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断是否有公告或者微农信信息
     *
     * @param sqlDb
     * @param type
     */
    private boolean isExsitMotice(SQLiteDatabase sqlDb, int type, String name) {
        Cursor cursor = sqlDb.rawQuery("select  " + MessageRecordDao.COLUMN_TIME_STAMP + " , " + MessageRecordDao
                .COLUMN_MSG_UNREAD_COUNT + " from " + MessageRecordDao.TABLE_NAME + " where " + MessageRecordDao
                .COLUMN_MSG_TYPE + " = " + type, null);
        if (cursor.moveToFirst()) {
            int count = cursor.getInt(1);
            otherMap.put(type, count);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 更新单聊提醒状态
     *
     * @param senderId
     * @param status
     */
    synchronized public void warnStatusChangeSingle(String senderId, int status) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues updateValues = new ContentValues();
        updateValues.put(MessageRecordDao.COLUMN_MSG_WARN_STATUS, status);
        String where = MessageRecordDao.COLUMN_MSG_SENDER_ID + "=?";
        String[] args = new String[]{status + ""};
        int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, where, args);
        LogUtil.d(TAG, String.format("更新单聊id 为 %s的提醒状态，结果为%d", senderId, result));
    }

    /**
     * 更新公告提醒状态
     *
     * @param senderId
     * @param status
     */
    public void warnStatusChangeSingle(String senderId, int status, String name) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues updateValues = new ContentValues();
        updateValues.put(MessageRecordDao.COLUMN_MSG_WARN_STATUS, status);
        String where = MessageRecordDao.COLUMN_MSG_SENDER_ID + "=?";
        String[] args = new String[]{status + ""};
        int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, where, args);
        LogUtil.d(TAG, String.format("更新单聊id 为 %s的提醒状态，结果为%d", senderId, result));
    }

    /**
     * 更新未读状态
     */
    synchronized public void updateUnreadStatus(String senderId, int chatType) {
        String sql = "";
        if (chatType == MsgType.NOTICE.toNumber()) {
        } else if (chatType == MsgType.WNX_MSG.toNumber()) {
            //w微农信信息
            sql = "UPDATE " + MessageRecordDao.TABLE_NAME + " SET " + MessageRecordDao.COLUMN_MSG_UNREAD_COUNT + " = " +
                    "0 WHERE " + MessageRecordDao.COLUMN_MSG_TYPE + " = '" + chatType + "'";
        } else if (chatType == MsgType.CHAT_SINGLE.toNumber()) {
            Log.d(TAG, "222");
            sql = "UPDATE " + MessageRecordDao.TABLE_NAME + " SET " + MessageRecordDao.COLUMN_MSG_UNREAD_COUNT + " = " +
                    "0 WHERE " + MessageRecordDao.COLUMN_MSG_SENDER_ID + " = '" + senderId + "' and " +
                    MessageRecordDao.COLUMN_MSG_TYPE + " = " + chatType;
            //单聊
        } else if (chatType == MsgType.CHAT_CROUP.toNumber()) {
            //群聊
            sql = "UPDATE " + MessageRecordDao.TABLE_NAME + " SET " + MessageRecordDao.COLUMN_MSG_UNREAD_COUNT + " = " +
                    "0 WHERE " + MessageRecordDao.COLUMN_MSG_GROUP_ID + " = '" + senderId + "'";
        }
        if (TextUtils.isEmpty(sql)) {
            return;
        }
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        sqlDb.execSQL(sql);
        LogUtil.d(TAG, String.format("更新d 为 %s的未读状态为已读", senderId));
    }

    /**
     * 更新消息提醒状态
     *
     * @param groupId
     * @param status
     */
    synchronized public void warnStatusChangeMessage(String groupId, int chatType, int status) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues updateValues = new ContentValues();
        updateValues.put(MessageRecordDao.COLUMN_MSG_WARN_STATUS, status);
        String where = "";
        if (chatType == MsgType.CHAT_SINGLE.toNumber()) {
            where = MessageRecordDao.COLUMN_MSG_SENDER_ID + "=?";
            where += " and " + MessageRecordDao.COLUMN_MSG_TYPE + " = " + chatType;
        } else if (chatType == MsgType.CHAT_CROUP.toNumber()) {
            where = MessageRecordDao.COLUMN_MSG_GROUP_ID + "=?";
            where += " and " + MessageRecordDao.COLUMN_MSG_TYPE + " = " + chatType;
        } else if (chatType == MsgType.WNX_MSG.toNumber()) {
            where = MessageRecordDao.COLUMN_MSG_TYPE + "= 1";
        }

        String[] args = new String[]{groupId + ""};
        int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, where, args);
        LogUtil.d(TAG, String.format("更新群聊id 为 %s的提醒状态，结果为%d", groupId, result));
    }

//    /**
//     * 更新微农信提醒状态
//     *
//     * @param groupId
//     * @param status
//     */
//    public void warnStatusChangeGroup(String groupId, int status, String name) {
//        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
//        ContentValues updateValues = new ContentValues();
//        updateValues.put(MessageRecordDao.COLUMN_MSG_WARN_STATUS, status);
//        String where = MessageRecordDao.COLUMN_MSG_RECEIVER_ID + "=?";
//        String[] args = new String[]{status + ""};
//        int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues, where, args);
//        LogUtil.d(TAG, String.format("更新群聊id 为 %s的提醒状态，结果为%d", groupId, result));
//    }


    /**
     * 删除某条单聊记录
     *
     * @param sendId
     */
    synchronized public void deleteChatSingle(String sendId) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String where = MessageRecordDao.COLUMN_MSG_SENDER_ID + "=? AND " + MessageRecordDao.COLUMN_MSG_TYPE + "=?";
        String[] args = new String[]{sendId, MsgType.CHAT_SINGLE.toNumber() + ""};
        int deleteResult = sqlDb.delete(MessageRecordDao.TABLE_NAME, where, args);
        LogUtil.d(TAG, String.format("删除单聊id 为 %s，结果为%d", sendId, deleteResult));

    }

    /**
     * 删除某条公告记录
     *
     * @param sendId
     */
    public void deleteChatSingle(String sendId, String name) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String where = MessageRecordDao.COLUMN_MSG_SENDER_ID + "=?";
        String[] args = new String[]{sendId + ""};
        int deleteResult = sqlDb.delete(MessageRecordDao.TABLE_NAME, where, args);
        LogUtil.d(TAG, String.format("删除单聊id 为 %s，结果为%d", sendId, deleteResult));

    }
/*


*
* */

    /**
     * 删除某条群聊记录
     *
     * @param
     */
    synchronized public void deleteChatGroup(String groupid) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String where = MessageRecordDao.COLUMN_MSG_GROUP_ID + "=?";
        String[] args = new String[]{groupid + ""};
        int deleteResult = sqlDb.delete(MessageRecordDao.TABLE_NAME, where, args);
        LogUtil.d(TAG, String.format("删除群聊id 为 %s，结果为%d", groupid, deleteResult));

    }


    /**
     * 置顶某条消息
     *
     * @param id chatType
     */
    synchronized public void topChatMessage(String id, int chatType) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        Cursor cursor = sqlDb.rawQuery("select max(" + MessageRecordDao.COLUMN_MSG_INDEX + ") as maxIndex from " +
                MessageRecordDao.TABLE_NAME, null);
        int maxIndex = 0;
        if (cursor.moveToFirst()) {
            maxIndex = cursor.getInt(0);
        }
        maxIndex++;
        LogUtil.d(maxIndex + "");
        ContentValues updateValues = new ContentValues();
        updateValues.put(MessageRecordDao.COLUMN_MSG_IS_SHOW, 1);
        updateValues.put(MessageRecordDao.COLUMN_MSG_INDEX, maxIndex);
        String where = (chatType == MsgType.CHAT_SINGLE.toNumber() ?
                MessageRecordDao.COLUMN_MSG_SENDER_ID :
                MessageRecordDao.COLUMN_MSG_GROUP_ID) + "=? and " + MessageRecordDao.COLUMN_MSG_TYPE + " = ?";
        LogUtil.d(where);
        int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues,
                where, new String[]{id, chatType + ""});
        LogUtil.d("result>>" + result);
    }

    /**
     * 取消置顶某条消息
     *
     * @param id chatType
     */
    synchronized public void cancelTopChatMessage(String id, int chatType) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues updateValues = new ContentValues();
        updateValues.put(MessageRecordDao.COLUMN_MSG_INDEX, 0);
        sqlDb.update(MessageRecordDao.TABLE_NAME, updateValues,
                (chatType == MsgType.CHAT_SINGLE.toNumber() ?
                        MessageRecordDao.COLUMN_MSG_SENDER_ID :
                        MessageRecordDao.COLUMN_MSG_GROUP_ID) + "=? and " + MessageRecordDao.COLUMN_MSG_TYPE + " = " +
                        "?", new String[]{id, chatType + ""});
    }

//    public static final String COLUMN_MSG_TYPE = "msg_type";
//    public static final String COLUMN_MSG_LOGO = "msg_logo";
//    public static final String COLUMN_MSG_SENDER_ID = "msg_sender_id";
//    public static final String COLUMN_MSG_SENDER_NAME = "msg_sender_name";
//    public static final String COLUMN_MSG_RECEIVER_ID = "msg_receiver_id";
//    public static final String COLUMN_MSG_RECEIVER_NAME = "msg_receiver_name";
//    public static final String COLUMN_MSG_UNREAD_COUNT = "msg_unread_count";
//    public static final String COLUMN_MSG_WARN_STATUS = "msg_warn_status";
//    public static final String COLUMN_MSG_LAST_TIME = "msg_last_time";
//    public static final String COLUMN_MSG_CONTENT_TYPE = "msg_content_type";
//    public static final String COLUMN_MSG_CONTENT = "msg_content";
//    public static final String COLUMN_MSG_SEND_STATUS = "msg_send_status";
//    public static final String COLUMN_MSG_GROUP_ID = "msg_group_id";
//    public static final String COLUMN_MSG_GROUP_NAME = "msg_group_name";
//    public static final String COLUMN_MSG_INDEX = "msg_index";
//    public static final String COLUMN_REMARK1 = "remark1";
//    public static final String COLUMN_REMARK2 = "remark2";
//    public static final String COLUMN_REMARK3 = "remark3";

    /**
     * 根据cursor获取实体类
     *
     * @param cursor
     * @return
     */
    private MessageEntity getEntityByCursor(Cursor cursor) {
        MessageEntity messageEntity = new MessageEntity();
        String insertTime = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_TIME_STAMP));
        int msg_type = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_TYPE));
        String logo = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_LOGO));
        String sender_id = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_SENDER_ID));
        String sender_name = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_SENDER_NAME));
        String receive_id = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_RECEIVER_ID));
        String receive_name = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_RECEIVER_NAME));
        int count = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT));
        int warn_status = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_WARN_STATUS));
        String msg_last_time = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_LAST_TIME));
        int msg_content_type = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_CONTENT_TYPE));
        String msg_content = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_CONTENT));
        int isShow = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_IS_SHOW));
        int msg_send_status = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_SEND_STATUS));
        String group_id = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_GROUP_ID));
        String group_name = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_GROUP_NAME));
        int group_type = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_GROUP_TYPE));
        String user_sex = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_USER_SEX));
        int group_member = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_GROUP_MEMBER));
        int msg_index = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_INDEX));
        messageEntity.inserttime = insertTime;
        messageEntity.msg_type = msg_type;
        messageEntity.msg_logo = logo;
        messageEntity.msg_sender_id = sender_id;
        messageEntity.msg_sender_name = sender_name;
        messageEntity.msg_receiver_id = receive_id;
        messageEntity.msg_receiver_name = receive_name;
        messageEntity.msg_unread_count = count;
        messageEntity.msg_warn_status = warn_status;
        messageEntity.msg_last_time = msg_last_time;
        messageEntity.msg_content_type = msg_content_type;
        messageEntity.msg_content = msg_content;
        messageEntity.msg_send_status = msg_send_status;
        messageEntity.msg_group_id = group_id;
        messageEntity.msg_group_name = group_name;
        messageEntity.group_type = group_type;
        messageEntity.group_member = group_member;
        messageEntity.user_sex = user_sex;
        messageEntity.msg_index = msg_index;
        messageEntity.isShow = isShow;
        return messageEntity;
    }

    /**
     * 获取所有单聊消息
     */
    synchronized public List<MessageEntity> getMsgList() {
        LogUtil.d(TAG, "getMsgList");
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        List<MessageEntity> messageEntities = new ArrayList<>();
        //先查询公告
//        String noticeSql = "SELECT *  FROM " + MessageRecordDao.TABLE_NAME + " WHERE " + MessageRecordDao
//                .COLUMN_MSG_TYPE + "=" +
//                MessageEntity.MsgType.NOTICE.toNumber()/* + " AND " + MessageRecordDao.COLUMN_MSG_IS_SHOW + " = 1"*/;
//        LogUtil.d(TAG, "noticeSql >>> " + noticeSql);
//        Cursor noticeCursor = sqlDb.rawQuery(noticeSql, null);
//        if (noticeCursor.moveToFirst()) {
//            MessageEntity noticeBean = getEntityByCursor(noticeCursor);
//            noticeBean.isCanSlide = false;
//            messageEntities.add(noticeBean);
//        }
//        //释放对象
//        closeDbAndCursor(noticeCursor);

        //查询单聊置顶
        String topSql = "SELECT * FROM " + MessageRecordDao.TABLE_NAME + " WHERE " +
                MessageRecordDao.COLUMN_MSG_INDEX + " > 0  AND (" +
                MessageRecordDao.COLUMN_MSG_TYPE + " = " + MsgType.CHAT_SINGLE.toNumber() + " OR (" +
                MessageRecordDao.COLUMN_MSG_TYPE + " = " + MsgType.CHAT_CROUP.toNumber() + " AND " +
                MessageRecordDao.COLUMN_MSG_GROUP_TYPE + " = " + Type.GroupType.TEMP_GROUP + ")) AND " +
                MessageRecordDao.COLUMN_MSG_IS_SHOW + " = 1 ORDER BY " +
                MessageRecordDao.COLUMN_MSG_INDEX + " DESC";
        LogUtil.d(TAG, "wubaojie>>>getMsgList: topsql : " + topSql);
        Cursor topCursor = sqlDb.rawQuery(topSql, null);
        while (topCursor.moveToNext()) {
            messageEntities.add(getEntityByCursor(topCursor));
        }
        //释放对象
        closeDbAndCursor(topCursor);

        //查询其他非置顶单聊 按照时间排序
        String otherSql = " SELECT * FROM " + MessageRecordDao.TABLE_NAME + " WHERE " +
                MessageRecordDao.COLUMN_MSG_INDEX + " = 0 AND (" +
                MessageRecordDao.COLUMN_MSG_TYPE + " = " + MsgType.CHAT_SINGLE.toNumber() + " OR (" +
                MessageRecordDao.COLUMN_MSG_TYPE + " = " + MsgType.CHAT_CROUP.toNumber() + " AND " +
                MessageRecordDao.COLUMN_MSG_GROUP_TYPE + " = " + Type.GroupType.TEMP_GROUP + ")) AND " +
                MessageRecordDao.COLUMN_MSG_IS_SHOW + " = 1 ORDER BY " +
                MessageRecordDao.COLUMN_MSG_LAST_TIME + " DESC";
        LogUtil.d(TAG, "wubaojie>>>getMsgList: othersql : " + otherSql);
        Cursor cursor = sqlDb.rawQuery(otherSql, null);
        while (cursor.moveToNext()) {
            MessageEntity messageEntity = getEntityByCursor(cursor);
//            if (messageEntity.msg_type == MessageEntity.MsgType.WNX_MSG.toNumber()) {
//                messageEntity.isCanSlide = false;
//            }
            messageEntities.add(messageEntity);
        }
        closeDbAndCursor(cursor);
        return messageEntities;
    }
//    /**
//     * 获取公告
//     */
//    public List<MessageEntity> getNoticeList() {
//        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
//        List<MessageEntity> messageEntities = new ArrayList<>();
//        //先查询公告
//        String noticeSql = "SELECT *  FROM " + WeinongxinListDao.TABLE_NAME + " WHERE " + WeinongxinListDao
// .COLUMN_MSG_TYPE + "=" + MessageEntity.MsgType.NOTICE.toNumber();
//        LogUtil.d(TAG, "noticeSql >>> " + noticeSql);
//        Cursor noticeCursor = sqlDb.rawQuery(noticeSql, null);
//        if (noticeCursor.moveToFirst()) {
//            messageEntities.add(getEntityByCursor(noticeCursor));
//        }
//        //释放对象
//        closeDbAndCursor(noticeCursor);
//        return messageEntities;
//    }
//    /**
//     * 获取wnx
//     */
//    synchronized public List<MessageEntity> getWNXList() {
//        LogUtil.d(TAG, "getMsgList");
//        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
//        List<MessageEntity> messageEntities = new ArrayList<>();
//        String noticeSql = "SELECT *  FROM " + MessageRecordDao.TABLE_NAME + " WHERE " + MessageRecordDao
// .COLUMN_MSG_TYPE + "=" + MessageEntity.MsgType.WNX_MSG.toNumber();
//        LogUtil.d(TAG, "noticeSql >>> " + noticeSql);
//        Cursor noticeCursor = sqlDb.rawQuery(noticeSql, null);
//        if (noticeCursor.moveToFirst()) {
//            messageEntities.add(getEntityByCursor(noticeCursor));
//        }
//        //释放对象
//        closeDbAndCursor(noticeCursor);
//
//        return messageEntities;
//    }

    public synchronized List<MessageEntity> getGroupList() {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        List<MessageEntity> messageEntities = new ArrayList<>();
        //查询群聊置顶
        String topSql = "SELECT * FROM " + MessageRecordDao.TABLE_NAME + " WHERE " +
                MessageRecordDao.COLUMN_MSG_INDEX + " > 0  AND " +
                MessageRecordDao.COLUMN_MSG_TYPE + " = " + MsgType.CHAT_CROUP.toNumber() + " AND " +
                MessageRecordDao.COLUMN_MSG_GROUP_TYPE + " <> " + Type.GroupType.TEMP_GROUP + " AND " +
                MessageRecordDao.COLUMN_MSG_IS_SHOW + " = 1 ORDER BY " +
                MessageRecordDao.COLUMN_MSG_INDEX + " DESC";
        LogUtil.d(TAG, "wubaojie>>>getGroupList: topsql : " + topSql);
        Cursor topCursor = sqlDb.rawQuery(topSql, null);
        while (topCursor.moveToNext()) {
            MessageEntity messageEntity = getEntityByCursor(topCursor);
            messageEntity.isCanSlide = true;
            messageEntities.add(getEntityByCursor(topCursor));
        }
        //释放对象
        closeDbAndCursor(topCursor);

        //查询其他非置顶群聊 按照时间排序
        String otherSql = " SELECT * FROM " + MessageRecordDao.TABLE_NAME + " WHERE " +
                MessageRecordDao.COLUMN_MSG_INDEX + " = 0 AND " +
                MessageRecordDao.COLUMN_MSG_TYPE + " = " + MsgType.CHAT_CROUP.toNumber() + " AND " +
                MessageRecordDao.COLUMN_MSG_GROUP_TYPE + " <> " + Type.GroupType.TEMP_GROUP + " AND " +
                MessageRecordDao.COLUMN_MSG_IS_SHOW + " = 1 ORDER BY " +
                MessageRecordDao.COLUMN_MSG_LAST_TIME + " DESC";
        LogUtil.d(TAG, "wubaojie>>>getGroupList: othersql : " + otherSql);
        Cursor cursor = sqlDb.rawQuery(otherSql, null);
        while (cursor.moveToNext()) {
            MessageEntity messageEntity = getEntityByCursor(cursor);
            messageEntity.isCanSlide = true;
            messageEntities.add(messageEntity);
        }
        closeDbAndCursor(cursor);
        return messageEntities;
    }

    /**
     * 单聊获得某条记录
     *
     * @param senderId
     * @return
     */
    synchronized public MessageEntity getMessageEntity(String senderId, int chatType) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();

        String selectSql = "SELECT *  FROM " + MessageRecordDao.TABLE_NAME + " WHERE " +
                (chatType == MsgType.CHAT_SINGLE.toNumber() ? MessageRecordDao.COLUMN_MSG_SENDER_ID :
                        MessageRecordDao.COLUMN_MSG_GROUP_ID) + "='" + senderId + "' AND " + MessageRecordDao
                .COLUMN_MSG_TYPE + "=" + chatType;

        LogUtil.d(selectSql);
        Cursor cursor = sqlDb.rawQuery(selectSql, null);
        LogUtil.d("cursor " + (cursor == null));
        try {
            if (cursor != null && cursor.moveToFirst()) {
                MessageEntity entity = getEntityByCursor(cursor);
                LogUtil.d(entity.toString());
                return entity;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public void updateGroupName(String groupId, String groupName) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE " + MessageRecordDao.TABLE_NAME + " SET " + MessageRecordDao.COLUMN_MSG_GROUP_NAME + " =" +
                " '" + groupName + "'  WHERE " + MessageRecordDao.COLUMN_MSG_GROUP_ID + " = '" + groupId + "'";
        LogUtil.d(sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 修改消息列表发送状态
     *
     * @param inserttime
     * @param status
     */
    synchronized public void updateMessageListStatus(String inserttime, int status) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + MessageRecordDao.TABLE_NAME + " SET " + MessageRecordDao.COLUMN_MSG_SEND_STATUS + "" +
                " = " + status + " WHERE " + MessageRecordDao.COLUMN_TIME_STAMP + " = '" + inserttime + "'";
        LogUtil.d(TAG, " 更新消息列表发送状态 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 修改某条单聊的发送状态
     *
     * @param senderid
     * @param status
     */
    synchronized public void updateMessageEntityStatus(String senderid, int status, int chatType) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + MessageRecordDao.TABLE_NAME + " SET " + MessageRecordDao.COLUMN_MSG_SEND_STATUS + "" +
                " = " + status + " WHERE " +
                (chatType == MsgType.CHAT_SINGLE.toNumber() ? MessageRecordDao.COLUMN_MSG_SENDER_ID :
                        MessageRecordDao.COLUMN_MSG_GROUP_ID) + " = '" + senderid + "'";
        LogUtil.d(TAG, " 更新消息列表发送状态 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 更新最新时间
     *
     * @param senderid
     * @param time
     * @param chatType
     */
    synchronized public void updateMessageEntityTime(String senderid, String time, int chatType) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + MessageRecordDao.TABLE_NAME + " SET " + MessageRecordDao.COLUMN_MSG_LAST_TIME + " =" +
                " '" + time + "'  WHERE " +
                (chatType == MsgType.CHAT_SINGLE.toNumber() ? MessageRecordDao.COLUMN_MSG_SENDER_ID :
                        MessageRecordDao.COLUMN_MSG_GROUP_ID) + " = '" + senderid + "'";
        LogUtil.d(TAG, " 更新消息列表最新时间 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }
    /**
     * MesssageListDao 结束
     */
    /**
     * ChatRecordDao 开始
     */

    synchronized public void insertMsgRecord(MsgRecordEntity recordEntity) {
        LogUtil.d(TAG, "insertMsgRecord " + recordEntity.msg_id);
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String inserttime;
        if (!TextUtils.isEmpty(recordEntity.inserttime)) {
            inserttime = recordEntity.inserttime;
        } else {
            inserttime = System.currentTimeMillis() + "";
        }
        if (!TextUtils.isEmpty(recordEntity.msg_id)) {
            //判断存在的话不用在插入
            Cursor qCursor = sqlDb.query(ChatRecordDao.TABLE_NAME, new String[]{ChatRecordDao.COLUMN_MSG_ID},
                    ChatRecordDao.COLUMN_MSG_ID + " = ?", new String[]{recordEntity.msg_id}, null, null, null);
            if (qCursor.moveToFirst()) {
                LogUtil.d("消息已经存在");
                return;
            } else {
                LogUtil.d("消息不存在");
            }
        }

        //判断是否需要存储附件
        boolean isNeedStoreFile = ChatFileEntity.isNeedSaveFile(recordEntity.msg_content_type);
        if (isNeedStoreFile) {
            //插入文件附件记录表
            recordEntity.mFileEntity.msg_id = recordEntity.msg_id;
            recordEntity.mFileEntity.file_type = recordEntity.msg_content_type;
            insertFileRecord(inserttime, recordEntity.mFileEntity);
            ContentValues insertValues = buildMsgRecordValues(recordEntity);
            insertValues.put(ChatRecordDao.COLUMN_INSERTTIME, inserttime);
            LogUtil.d(TAG, insertValues.toString());
            //插入聊天记录表
            long result = sqlDb.insert(ChatRecordDao.TABLE_NAME, null, insertValues);
            LogUtil.d(TAG, String.format("插入聊天记录表 SenderName 为 %s的聊天记录，结果为%d", recordEntity.msg_sender_name, result));
        } else {
            //插入聊天记录表
            ContentValues insertValues = buildMsgRecordValues(recordEntity);
            insertValues.put(ChatRecordDao.COLUMN_INSERTTIME, inserttime);
            LogUtil.d(TAG, insertValues.toString());
            long result = sqlDb.insert(ChatRecordDao.TABLE_NAME, null, insertValues);
            LogUtil.d(TAG, String.format("插入聊天记录表 SenderName 为 %s的聊天记录，结果为%d", recordEntity.msg_sender_name, result));
        }
    }

    /**
     * 修改聊天记录 撤回使用
     *
     * @param time
     * @param entity
     */
    public void updateChatRecordByInserttime(String time, MsgRecordEntity entity) {
        if (TextUtils.isEmpty(time))
            return;
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues updateValues = buildMsgRecordValues(entity);
        sqlDb.update(ChatRecordDao.TABLE_NAME, updateValues, ChatRecordDao.COLUMN_INSERTTIME + " = ?", new
                String[]{time});
        LogUtil.d("修改成功");
    }


    synchronized public List<MsgRecordEntity> queryMsgRecordSingleAndGroup(String id, int chatType, int pageIndex, String formId) {
        List<MsgRecordEntity> entities = new ArrayList<>();
        SQLiteDatabase sqlDb = dbHelper.getReadableDatabase();
        String querySql =
                "SELECT * FROM " +
                        "(SELECT * FROM " + ChatRecordDao.TABLE_NAME +
                        "  WHERE " + ((MsgType.CHAT_SINGLE.toNumber() == chatType || MsgType.CHAT_QAC_FORM.toNumber() == chatType) ? ChatRecordDao
                        .COLUMN_MSG_SENDER_ID : ChatRecordDao.COLUMN_MSG_GROUP_ID) + " = '" + id +
                        "' AND " + ChatRecordDao.COLUMN_MSG_TYPE + " = " + chatType + (TextUtils.isEmpty(formId) ? "" : (" AND " + ChatRecordDao.COLUMN_FORM_ID + " = '" + formId + "'")) +
                        " ORDER BY " + ChatRecordDao.COLUMN_MSG_SEND_TIME + " DESC   LIMIT " + PageUtil.PAGE_SIZE + "" +
                        " OFFSET " + pageIndex * PageUtil.PAGE_SIZE + ") ORDER BY " + ChatRecordDao
                        .COLUMN_MSG_SEND_TIME + " ASC ";
        LogUtil.d(TAG, " querySql " + querySql);
        Cursor recordCursor = sqlDb.rawQuery(querySql, null);
        while (recordCursor.moveToNext()) {
            MsgRecordEntity entity = new MsgRecordEntity();
            entity.msg_type = chatType;
            int content_type = recordCursor.getInt(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_MSG_CONTENT_TYPE));
            entity.msg_content_type = content_type;
            String msg_id = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_MSG_ID));
            String insertime = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_INSERTTIME));
            entity.msg_id = msg_id;
            entity.inserttime = insertime;
            if (ChatFileEntity.isNeedSaveFile(content_type)) {
                //文件记录表中有数据
                entity.mFileEntity = queryChatFileByTime(insertime);
            }
            entity.msg_sender_id = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao
                    .COLUMN_MSG_SENDER_ID));
            entity.msg_group_id = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao
                    .COLUMN_MSG_GROUP_ID));
            entity.msg_sender_name = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao
                    .COLUMN_MSG_SENDER_NAME));
            entity.msg_logo = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_MSG_SENDER_LOGO));
            entity.msg_content = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_MSG_TEXT));
            entity.msg_last_time = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao
                    .COLUMN_MSG_SEND_TIME));
            entity.msg_send_status = recordCursor.getInt(recordCursor.getColumnIndex(ChatRecordDao
                    .COLUMN_MSG_SEND_STATUS));
//            entity.tip_type = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_MSG_TIP_TYPE));
            entity.is_mine = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_IS_SENDER_MINE));

            entity.form_id = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_FORM_ID));
            entity.form_url = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_FORM_URL));
            entity.form_type = recordCursor.getInt(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_FORM_TYPE));
            entity.form_status = recordCursor.getInt(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_FORM_STATUS));
            entities.add(entity);
        }
        return entities;
    }


    /**
     * 修改聊天记录发送状态
     *
     * @param inserttime
     * @param status
     */
    synchronized public void updateMsgSendStatus(String inserttime, int status) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + ChatRecordDao.TABLE_NAME + " SET " + ChatRecordDao.COLUMN_MSG_SEND_STATUS + " = " +
                status + " WHERE " + ChatRecordDao.COLUMN_INSERTTIME + " = '" + inserttime + "'";
        LogUtil.d(TAG, " 更新聊天记录发送状态 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 修改所发送聊天记录的消息id
     *
     * @param inserttime
     * @param msg_id
     */
    synchronized public void updateMsgSendMsgid(String inserttime, String msg_id) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + ChatRecordDao.TABLE_NAME + " SET " + ChatRecordDao.COLUMN_MSG_ID + " = '" + msg_id
                + "'  WHERE " + ChatRecordDao.COLUMN_INSERTTIME + " = '" + inserttime + "'";
        LogUtil.d(TAG, " 更新聊天记录发送状态 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 更新消息发送时间
     *
     * @param inserttime
     * @param time
     */
    synchronized public void updateMsgSendTime(String inserttime, String time) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        if (!TextUtils.isEmpty(time)) {
            String sql = "UPDATE  " + ChatRecordDao.TABLE_NAME + " SET " + ChatRecordDao.COLUMN_MSG_SEND_TIME + " = '" +
                    time + "'  WHERE " + ChatRecordDao.COLUMN_INSERTTIME + " = '" + inserttime + "'";
            LogUtil.d(TAG, " 更新聊天记录发送状态 sql  >>" + sql);
            sqlDb.execSQL(sql);
        }

    }

    /**
     * 删除某条记录
     *
     * @param inserttime
     */
    public int deleteOneChatRecordByTime(String inserttime) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        int result = sqlDb.delete(ChatRecordDao.TABLE_NAME, ChatRecordDao.COLUMN_INSERTTIME + " = ?", new
                String[]{inserttime});
        LogUtil.d(TAG, " 删除聊天记录  sql  >>" + result);
        return result;
    }


    /**
     * @param id
     * @param chatType
     */
    public int deleteChatRecord(String id, int chatType) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        int result = sqlDb.delete(ChatRecordDao.TABLE_NAME,
                (chatType == MsgType.CHAT_CROUP.toNumber()
                        ? ChatRecordDao.COLUMN_MSG_GROUP_ID : ChatRecordDao.COLUMN_MSG_SENDER_ID) + " = ?",
                new String[]{id});

        LogUtil.d(TAG, " 删除聊天记录  result >>" + result + " id " + id + " chatType " + chatType);
        return result;
    }

    /**
     * @param id
     * @param formId
     */
    public void clearChatRecordUnreadCount(String id, String formId) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE " + ChatRecordDao.TABLE_NAME + " SET " + ChatRecordDao.COLUMN_MSG_UNREAD_FLAG + " = '1'" +
                "  WHERE " + ChatRecordDao.COLUMN_MSG_SENDER_ID + " = '" + id + "' AND " + ChatRecordDao.COLUMN_FORM_ID + " = '" + formId +
                "' AND  " + ChatRecordDao.COLUMN_MSG_TYPE + " = " + MsgType.CHAT_QAC_FORM.toNumber();
        sqlDb.execSQL(sql);
    }

    public void clearChatRecord(String id, int chatType) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        int result = sqlDb.delete(ChatRecordDao.TABLE_NAME,
                (chatType == MsgType.CHAT_CROUP.toNumber()
                        ? ChatRecordDao.COLUMN_MSG_GROUP_ID : ChatRecordDao.COLUMN_MSG_SENDER_ID) + " = ?",
                new String[]{id});
        LogUtil.d(TAG, " 删除聊天记录  result >>" + result + " id " + id + " chatType " + chatType);
    }

    public int deleteOneChatRecordById(String msgId) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        int result = sqlDb.delete(ChatRecordDao.TABLE_NAME, ChatRecordDao.COLUMN_MSG_ID + " = ?", new String[]{msgId});
        LogUtil.d(TAG, " 删除聊天记录  sql  >>" + result);
        return result;
    }

    public int getChatRecordFormUnreadCount(String sender_id, String formId) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "SELECT COUNT(*)  FROM " + ChatRecordDao.TABLE_NAME
                + " WHERE " + ChatRecordDao.COLUMN_MSG_SENDER_ID + " = '" + sender_id +
                "' AND " + ChatRecordDao.COLUMN_FORM_ID + " ='" + formId + "'"
                + " AND " + ChatRecordDao.COLUMN_MSG_UNREAD_FLAG + " = '0'";
        LogUtil.d(TAG, " 得到聊天记录相关免疫申报单的未读数量 sql  >>" + sql);
        Cursor recordCursor = sqlDb.rawQuery(sql, null);
        int unreadCount = 0;
        while (recordCursor.moveToNext()) {
            unreadCount = recordCursor.getInt(0);

        }
        return unreadCount;
    }

    /**
     * \构建消息记录ContentValues
     *
     * @param entity
     * @return
     */
    private ContentValues buildMsgRecordValues(MsgRecordEntity entity) {
        ContentValues inserValues = new ContentValues();
        inserValues.put(ChatRecordDao.COLUMN_MSG_ID, entity.msg_id);
        inserValues.put(ChatRecordDao.COLUMN_MSG_SENDER_ID, entity.msg_sender_id);
        inserValues.put(ChatRecordDao.COLUMN_MSG_SENDER_NAME, entity.msg_sender_name);
        inserValues.put(ChatRecordDao.COLUMN_MSG_SENDER_LOGO, entity.msg_logo);
        if (!ChatFileEntity.isNeedSaveFile(entity.msg_content_type)) {
            inserValues.put(ChatRecordDao.COLUMN_MSG_TEXT, entity.msg_content);
        }
        inserValues.put(ChatRecordDao.COLUMN_MSG_CONTENT_TYPE, entity.msg_content_type);
        inserValues.put(ChatRecordDao.COLUMN_MSG_SEND_TIME, entity.msg_last_time);
        inserValues.put(ChatRecordDao.COLUMN_MSG_SEND_STATUS, entity.msg_send_status);
        inserValues.put(ChatRecordDao.COLUMN_MSG_TIP_TYPE, entity.tip_type);
        inserValues.put(ChatRecordDao.COLUMN_MSG_TYPE, entity.msg_type);
        inserValues.put(ChatRecordDao.COLUMN_MSG_GROUP_ID, entity.msg_group_id);
        inserValues.put(ChatRecordDao.COLUMN_MSG_GROUP_NAME, entity.msg_group_name);
        inserValues.put(ChatRecordDao.COLUMN_IS_SENDER_MINE, entity.is_mine);

        inserValues.put(ChatRecordDao.COLUMN_FORM_ID, entity.form_id);
        inserValues.put(ChatRecordDao.COLUMN_FORM_URL, entity.form_url);
        inserValues.put(ChatRecordDao.COLUMN_FORM_TYPE, entity.form_type);
        inserValues.put(ChatRecordDao.COLUMN_FORM_STATUS, entity.form_status);
        if (entity.isRead) {
            inserValues.put(ChatRecordDao.COLUMN_MSG_UNREAD_FLAG, "1");
        } else {
            inserValues.put(ChatRecordDao.COLUMN_MSG_UNREAD_FLAG, "0");
        }

        return inserValues;
    }

    /**
     * 构建消息记录 文件附件ContentValues
     *
     * @param chatFileEntity
     * @return
     */
    private ContentValues buildChatFileValues(ChatFileEntity chatFileEntity) {
        ContentValues inserValues = new ContentValues();
        inserValues.put(ChatFileDao.COLUMN_MSG_ID, chatFileEntity.msg_id);
        inserValues.put(ChatFileDao.COLUMN_FILE_NAME, chatFileEntity.file_name);
        inserValues.put(ChatFileDao.COLUMN_FILE_URL_LOCAL, chatFileEntity.file_url_local);
        inserValues.put(ChatFileDao.COLUMN_FILE_URL_REMOTE, chatFileEntity.file_url_remote);
        inserValues.put(ChatFileDao.COLUMN_FILE_SIZE, chatFileEntity.file_size);
        inserValues.put(ChatFileDao.COLUMN_FILE_DOWNLOAD_STATUS, chatFileEntity.file_download_status);
        inserValues.put(ChatFileDao.COLUMN_FILE_TYPE, chatFileEntity.file_type);
        inserValues.put(ChatFileDao.COLUMN_LNG, chatFileEntity.lng);
        inserValues.put(ChatFileDao.COLUMN_LAT, chatFileEntity.lat);
        inserValues.put(ChatFileDao.COLUMN_MSG_DUTIME, chatFileEntity.msg_dutime);
        inserValues.put(ChatFileDao.COLUMN_ADDRESS_DESC, chatFileEntity.address_desc);
        inserValues.put(ChatFileDao.COLUMN_IS_MEDIA_PLAYED, chatFileEntity.isMediaPlayed);
        return inserValues;

    }

    /**
     * 操作附件表
     */
    synchronized public void insertFileRecord(String time, ChatFileEntity chatFileEntity) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues insertValues = buildChatFileValues(chatFileEntity);
        insertValues.put(ChatFileDao.COLUMN_INSERTTIME, time);
        long result = sqlDb.insert(ChatFileDao.TABLE_NAME, null, insertValues);
        LogUtil.d(TAG, String.format("插入聊天记录文件附件表 名字为 %s的附件，结果为%d", chatFileEntity.file_name, result));
    }

    /**
     * 更新本地url
     *
     * @param insertime
     * @param path
     */
    synchronized public void updateFileLocalPathByTime(String insertime, String path) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + ChatFileDao.TABLE_NAME + " SET " + ChatFileDao.COLUMN_FILE_URL_LOCAL + " = '" +
                path + "' WHERE " + ChatFileDao.COLUMN_INSERTTIME + " = '" + insertime + "'";
        LogUtil.d(TAG, " 更新文件本地下载路径 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 添加方法  下载的附件 通过msg_id 更改状态，
     *
     * @param insertime
     * @param path
     */
    synchronized public void updateFileLocalPathByMsgId(String insertime, String path) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + ChatFileDao.TABLE_NAME + " SET " + ChatFileDao.COLUMN_FILE_URL_LOCAL + " = '" +
                path + "' WHERE " + ChatFileDao.COLUMN_INSERTTIME + " = '" + insertime + "'";
        LogUtil.d(TAG, " 更新文件本地下载路径 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 更新文件下载状态
     */
    synchronized public void updateFileDownLoadStausById(String msg_id, int status) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + ChatFileDao.TABLE_NAME + " SET " + ChatFileDao.COLUMN_FILE_DOWNLOAD_STATUS + " = "
                + status + " WHERE " + ChatFileDao.COLUMN_MSG_ID + " = '" + msg_id + "'";
        LogUtil.d(TAG, " 更新文件下载状态发送状态 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 更新文件下载状态
     */
    synchronized public void updateFileDownLoadStausByTime(String insertime, int status) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + ChatFileDao.TABLE_NAME + " SET " + ChatFileDao.COLUMN_FILE_DOWNLOAD_STATUS + " = "
                + status + " WHERE " + ChatFileDao.COLUMN_INSERTTIME + " = '" + insertime + "'";
        LogUtil.d(TAG, " 更新文件下载状态发送状态 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 更新文件服务器地址
     */
    synchronized public void updateFileRemotePathByTime(String inserttime, String path) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + ChatFileDao.TABLE_NAME + " SET " + ChatFileDao.COLUMN_FILE_URL_REMOTE + " = '" +
                path + "'  WHERE " + ChatFileDao.COLUMN_INSERTTIME + " = '" + inserttime + "'";
        LogUtil.d(TAG, " 更新文件服务器地址 sql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    /**
     * 更新文件msg_id
     */
    synchronized public void updateFileMsgIdByTime(String inserttime, String id) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String sql = "UPDATE  " + ChatFileDao.TABLE_NAME + " SET " + ChatFileDao.COLUMN_MSG_ID + " = '" + id + "'  " +
                "WHERE " + ChatFileDao.COLUMN_INSERTTIME + " = '" + inserttime + "'";
        LogUtil.d(TAG, " 更新文件msg_idsql  >>" + sql);
        sqlDb.execSQL(sql);
    }

    public ChatFileEntity queryChatFileByMsgId(String msg_id) {
        SQLiteDatabase sqlDb = dbHelper.getReadableDatabase();
        ChatFileEntity entity = new ChatFileEntity();
        String queryFile = "select * from " + ChatFileDao.TABLE_NAME + " where " + ChatFileDao.COLUMN_MSG_ID + " = "
                + msg_id;
        Cursor fileCursor = sqlDb.rawQuery(queryFile, null);
        if (fileCursor.moveToFirst()) {
            entity = getFileEntityByCursor(fileCursor);
        }
        return entity;
    }

    synchronized public ChatFileEntity queryChatFileByTime(String time) {
        SQLiteDatabase sqlDb = dbHelper.getReadableDatabase();
        ChatFileEntity entity = new ChatFileEntity();
        String queryFile = "SELECT * FROM " + ChatFileDao.TABLE_NAME + " WHERE " + ChatFileDao.COLUMN_INSERTTIME + " " +
                "= '" + time + "'";
        Cursor fileCursor = sqlDb.rawQuery(queryFile, null);
        if (fileCursor.moveToFirst()) {
            entity = getFileEntityByCursor(fileCursor);
        }
        return entity;
    }

    public ChatFileEntity getFileEntityByCursor(Cursor cursor) {
        ChatFileEntity fileEntity = new ChatFileEntity();
        int contentType = cursor.getInt(cursor.getColumnIndex(ChatFileDao.COLUMN_FILE_TYPE));
        if (contentType == ContentType.LOCATION.toNumber()) {
            //地址
            fileEntity.lng = cursor.getString(cursor.getColumnIndex(ChatFileDao.COLUMN_LNG));
            fileEntity.lat = cursor.getString(cursor.getColumnIndex(ChatFileDao.COLUMN_LAT));
            fileEntity.address_desc = cursor.getString(cursor.getColumnIndex(ChatFileDao.COLUMN_ADDRESS_DESC));
        } else if (contentType == ContentType.VOICE.toNumber()) {
            //语音
            fileEntity.msg_dutime = cursor.getInt(cursor.getColumnIndex(ChatFileDao.COLUMN_MSG_DUTIME));
            fileEntity.isMediaPlayed = cursor.getInt(cursor.getColumnIndex(ChatFileDao.COLUMN_IS_MEDIA_PLAYED));
        }

        fileEntity.file_type = contentType;
        fileEntity.msg_id = cursor.getString(cursor.getColumnIndex(ChatFileDao.COLUMN_MSG_ID));
        fileEntity.file_name = cursor.getString(cursor.getColumnIndex(ChatFileDao.COLUMN_FILE_NAME));
        fileEntity.file_url_local = cursor.getString(cursor.getColumnIndex(ChatFileDao.COLUMN_FILE_URL_LOCAL));
        fileEntity.file_url_remote = cursor.getString(cursor.getColumnIndex(ChatFileDao.COLUMN_FILE_URL_REMOTE));
        fileEntity.file_size = cursor.getString(cursor.getColumnIndex(ChatFileDao.COLUMN_FILE_SIZE));
        fileEntity.file_download_status = cursor.getInt(cursor.getColumnIndex(ChatFileDao.COLUMN_FILE_DOWNLOAD_STATUS));
        return fileEntity;
    }

    /**
     * ==============机构成员begin==============
     **/
    public void insertOrgUser(OrgDeptUserBean bean) {
        if (TextUtils.isEmpty(bean.user_id)) {
            LogUtil.d("userId不能为空");
            return;
        }
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String queryUser = "select * from " + OrgAllUserDao.TABLE_NAME + " where " + OrgAllUserDao.COLUMN_FRIEND_ID +
                " = '" + bean.user_id + "'";
        Cursor queryCursor = sqlDb.rawQuery(queryUser, null);
        if (queryCursor.moveToFirst()) {

            if (OrgDeptUserBean.UserStatus.Update.toNumber() == bean.user_status) {
                ContentValues userValues = new ContentValues();
                userValues.put(OrgAllUserDao.COLUMN_FRIEND_DEPT_ID, bean.dept_id);
                userValues.put(OrgAllUserDao.COLUMN_FRIEND_NAME, bean.user_name);
                userValues.put(OrgAllUserDao.COLUMN_FRIEND_DEPT_NAME, bean.dept_name);
                userValues.put(OrgAllUserDao.COLUMN_FRIEND_LOGO, bean.user_logo);
                userValues.put(OrgAllUserDao.COLUMN_FRIEND_SEX, bean.user_sex);
                int updateResult = sqlDb.update(OrgAllUserDao.TABLE_NAME, userValues, OrgAllUserDao.COLUMN_FRIEND_ID
                        + "= ? ", new String[]{bean.user_id});
                LogUtil.d(TAG, " updateResult  >>" + updateResult);
            } else if (OrgDeptUserBean.UserStatus.Delete.toNumber() == bean.user_status) {
                //删除
                int deleteResult = sqlDb.delete(OrgAllUserDao.TABLE_NAME, OrgAllUserDao.COLUMN_FRIEND_ID + "= ? ",
                        new String[]{bean.user_id});
                LogUtil.d(TAG, " deleteResult  >>" + deleteResult);
            }
        } else {
            if (OrgDeptUserBean.UserStatus.Delete.toNumber() == bean.user_status) {
                return;
            }
            ContentValues userValues = new ContentValues();
            userValues.put(OrgAllUserDao.COLUMN_FRIEND_ID, bean.user_id);
            userValues.put(OrgAllUserDao.COLUMN_FRIEND_DEPT_ID, bean.dept_id);
            userValues.put(OrgAllUserDao.COLUMN_FRIEND_NAME, bean.user_name);
            userValues.put(OrgAllUserDao.COLUMN_FRIEND_DEPT_NAME, bean.dept_name);
            userValues.put(OrgAllUserDao.COLUMN_FRIEND_LOGO, bean.user_logo);
            userValues.put(OrgAllUserDao.COLUMN_FRIEND_SEX, bean.user_sex);
            long insertResult = sqlDb.insert(OrgAllUserDao.TABLE_NAME, null, userValues);
            LogUtil.d(TAG, " r人员insertResult  >>" + insertResult);
        }

    }

    public ArrayList<OrgDeptUserBean> getOrgUserList() {
        ArrayList<OrgDeptUserBean> dataList = new ArrayList<>();
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String queryUser = "select * from " + OrgAllUserDao.TABLE_NAME;
        Cursor queryCursor = sqlDb.rawQuery(queryUser, null);
        while (queryCursor.moveToNext()) {
            OrgDeptUserBean bean = new OrgDeptUserBean();
            bean.user_id = queryCursor.getString(queryCursor.getColumnIndex(OrgAllUserDao.COLUMN_FRIEND_ID));
            bean.user_name = queryCursor.getString(queryCursor.getColumnIndex(OrgAllUserDao.COLUMN_FRIEND_NAME));
            bean.user_logo = queryCursor.getString(queryCursor.getColumnIndex(OrgAllUserDao.COLUMN_FRIEND_LOGO));
            bean.dept_id = queryCursor.getString(queryCursor.getColumnIndex(OrgAllUserDao.COLUMN_FRIEND_DEPT_ID));
            bean.user_sex = queryCursor.getString(queryCursor.getColumnIndex(OrgAllUserDao.COLUMN_FRIEND_SEX));
            bean.dept_name = queryCursor.getString(queryCursor.getColumnIndex(OrgAllUserDao.COLUMN_FRIEND_DEPT_NAME));
            dataList.add(bean);

//            MsgRecordEntity entity = new MsgRecordEntity();
//            entity.msg_type = MessageEntity.MsgType.CHAT_SINGLE.toNumber();
//            int content_type = recordCursor.getInt(recordCursor.getColumnIndex(ChatRecordDao
// .COLUMN_MSG_CONTENT_TYPE));
//            entity.msg_content_type = content_type;
//            String msg_id = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_MSG_ID));
//            String insertime = recordCursor.getString(recordCursor.getColumnIndex(ChatRecordDao.COLUMN_INSERTTIME));
//            entity.msg_id = msg_id;
//            entity.inserttime = insertime;
        }
        return dataList;
    }

    /**==============机构成员end==============**/

    /**
     * 修改音频播放状态的标志
     *
     * @param inserttime
     * @param flag
     */
    public void updateFileIsPlayedFlag(String inserttime, int flag) {
        SQLiteDatabase sqlDb = dbHelper.getReadableDatabase();
        String sql = "UPDATE  " + ChatFileDao.TABLE_NAME + " SET " + ChatFileDao.COLUMN_IS_MEDIA_PLAYED + " = " +
                flag + "  WHERE " + ChatFileDao.COLUMN_INSERTTIME + " = '" + inserttime + "'";
        LogUtil.d(TAG, " 更新文件播放状态  >>" + sql);
        sqlDb.execSQL(sql);
    }


    private synchronized void closeDbAndCursor(Cursor cursor) {
        if (cursor != null) {
            try {
                cursor.close();
            } catch (Exception e) {
                e.printStackTrace();
                cursor = null;
            }
        }
    }

    synchronized public void closeDB() {
        if (dbHelper != null) {
            dbHelper.closeDB();
        }
        dbMgr = null;
    }

    /**
     * 增加一条通知公告
     *
     * @param wnxBean
     */
    public void insertWnxNotice(WNXBean wnxBean) {
        if (TextUtils.isEmpty(wnxBean.inserttime)) {
            wnxBean.inserttime = System.currentTimeMillis() + "";
        }
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(NoticeDao.COLUMN_TIME_STAMP, wnxBean.inserttime);
        contentValues.put(NoticeDao.COLUMN_MSG_CONTENT, wnxBean.content);
        contentValues.put(NoticeDao.COLUMN_MSG_ID, wnxBean.msg_id);
        contentValues.put(NoticeDao.COLUMN_MSG_CONTENT_TYPE, wnxBean.msg_content_type);
        contentValues.put(NoticeDao.COLUMN_MSG_KIND, wnxBean.msg_kind);
        contentValues.put(NoticeDao.COLUMN_MSG_LOGO, wnxBean.msg_logo);
        contentValues.put(NoticeDao.COLUMN_MSG_SEND_TIME, wnxBean.msg_send_time);
        contentValues.put(NoticeDao.COLUMN_MSG_SENDER_ID, wnxBean.msg_sender_id);
        contentValues.put(NoticeDao.COLUMN_MSG_SENDER_NAME, wnxBean.msg_sender_name);
        contentValues.put(NoticeDao.COLUMN_MSG_UNREAD_FLAG, wnxBean.msg_unread_flag);
        contentValues.put(NoticeDao.COLUMN_MSG_TITLE, wnxBean.msg_title);
        contentValues.put(NoticeDao.COLUMN_MSG_TYPE, wnxBean.msg_type);
        contentValues.put(NoticeDao.COLUMN_REMARK3, wnxBean.bean_type);
        if (!TextUtils.isEmpty(wnxBean.msg_id) && isExsitWnx(wnxBean.msg_id)) {
            int resut = sqlDb.update(NoticeDao.TABLE_NAME, contentValues,
                    NoticeDao.COLUMN_MSG_ID + " = ? ",
                    new String[]{wnxBean.msg_id});
            LogUtil.d(TAG, String.format("更新微农信表 发送人名字为 %s ，结果为%d", wnxBean.msg_sender_name, resut));
        } else {
            long resut = sqlDb.insert(NoticeDao.TABLE_NAME, null, contentValues);
            LogUtil.d(TAG, String.format("插入微农信表 发送人名字为 %s ，结果为%d", wnxBean.msg_sender_name, resut) + " wnxBean " +
                    ".sendTime " + wnxBean.msg_send_time);
        }
    }

    private boolean isExsitWnx(String msgId) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        Cursor rowCur = sqlDb.rawQuery(" select * from " + NoticeDao.TABLE_NAME +
                " where " + NoticeDao.COLUMN_MSG_ID + " =  ? ", new String[]{msgId});
        if (rowCur.moveToFirst()) {
            LogUtil.d(" exsit ");
            return true;
        } else {
            LogUtil.d(" not exsit ");
            return false;
        }

    }

    /**
     * 删除一条通知公告
     *
     * @param wnxBean
     */
    public void deleleWnxNotice(WNXBean wnxBean) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        long result = sqlDb.delete(NoticeDao.TABLE_NAME, NoticeDao.COLUMN_TIME_STAMP + "=?", new String[]{wnxBean
                .inserttime});
        LogUtil.e(TAG, "wubaojie>>>" + "deleleWnxNotice: " + wnxBean.inserttime + " : " + result);
    }

    /**
     * 删除微农信的空数据
     *
     * @param senderId
     */
    public void deleleBlankWnx(String senderId) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        long result = sqlDb.delete(NoticeDao.TABLE_NAME, NoticeDao.COLUMN_MSG_SENDER_ID + "=?  and " + NoticeDao
                .COLUMN_REMARK3 + " = 1 ", new String[]{senderId
        });
        LogUtil.e(TAG, "wubaojie>>>" + "deleleBlankWnx: " + senderId + " : " + result);
    }

    public void deleleAllWnxNotice(String depId) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        long result = sqlDb.delete(NoticeDao.TABLE_NAME, NoticeDao.COLUMN_MSG_TYPE + "=? AND " + NoticeDao
                .COLUMN_MSG_SENDER_ID + "=? AND " + NoticeDao.COLUMN_REMARK3 + " <> 1 ", new String[]{MsgType.WNX_MSG
                .toNumber() + "", depId});
        LogUtil.e(TAG, "wubaojie>>>" + "deleleWnxNotice:" + result);
    }


    public void updateWnxUnread(String inserttime, int flag) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(NoticeDao.COLUMN_MSG_UNREAD_FLAG, flag);
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        int result = sqlDb.update(NoticeDao.TABLE_NAME, contentValues, NoticeDao.COLUMN_TIME_STAMP + " =  ?", new
                String[]{flag + ""});
        LogUtil.d("更改未读状态>>>" + result);
    }

    private WNXBean buildNoticeDaoByCusor(Cursor cursor) {
//        if (TextUtils.isEmpty(cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_CONTENT)))) {
//
//        }else {
//
//        }
        WNXBean bean = new WNXBean();
        bean.inserttime = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_TIME_STAMP));
        bean.msg_sender_name = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_SENDER_NAME));
        bean.msg_sender_id = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_SENDER_ID));
        bean.msg_send_time = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_SEND_TIME));
        bean.content = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_CONTENT));
        bean.msg_content_type = cursor.getInt(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_CONTENT_TYPE));
        bean.msg_id = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_ID));
        bean.msg_kind = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_KIND));
        bean.msg_logo = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_LOGO));
        bean.msg_type = cursor.getInt(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_TYPE));
        bean.bean_type = cursor.getInt(cursor.getColumnIndex(NoticeDao.COLUMN_REMARK3));

        bean.msg_unread_flag = cursor.getInt(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_UNREAD_FLAG));
        bean.msg_title = cursor.getString(cursor.getColumnIndex(NoticeDao.COLUMN_MSG_TITLE));
        return bean;
    }

    /**
     * 获取公告列表
     *
     * @return
     */
    public ArrayList<WNXBean> getNoticeList() {
        //排序数序为先读取未读在读取已读，并且都按照时间排序
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ArrayList<WNXBean> beanList = new ArrayList<>();
        String unReadSql = " select * from " + NoticeDao.TABLE_NAME +
                " where  " + NoticeDao.COLUMN_MSG_TYPE + " = " + MsgType.NOTICE.toNumber() +
                " order by " + NoticeDao.COLUMN_MSG_UNREAD_FLAG + " ASC ," + NoticeDao.COLUMN_MSG_SEND_TIME + " DESC";

        LogUtil.d("unReadSql>>" + unReadSql);
        Cursor unreadCur = sqlDb.rawQuery(unReadSql, null);
        while (unreadCur.moveToNext()) {
            WNXBean bean = buildNoticeDaoByCusor(unreadCur);
            bean.isCanSlide = true;//再这里设置是否可以左滑删除
            beanList.add(bean);
        }
        closeDbAndCursor(unreadCur);
        return beanList;
    }

    /**
     * 获取通知公告所有未读数
     *
     * @return
     */
    public int getNoticeUnreadCount() {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String unReadSql = " select count(*) from " + NoticeDao.TABLE_NAME + " where  " +
                NoticeDao.COLUMN_MSG_TYPE + " = " + MsgType.NOTICE.toNumber() + " and  " +
                NoticeDao.COLUMN_MSG_UNREAD_FLAG + " = " + 0;

        Cursor unreadCur = sqlDb.rawQuery(unReadSql, null);
        int i = 0;
        while (unreadCur.moveToNext()) {
            i = unreadCur.getInt(0);
        }
        closeDbAndCursor(unreadCur);
        return i;
    }

    /**
     * 获取微农信未读数量,(目前不需要数量只需要是否已读未读)
     *
     * @return 0 : 未读;1 : 已读
     */
    public int getWNXUnreadStatue() {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();

        String unReadSql = " select " + MessageRecordDao.COLUMN_MSG_UNREAD_COUNT + " from " +
                MessageRecordDao.TABLE_NAME + " where  " +
                MessageRecordDao.COLUMN_MSG_TYPE + " = " + MsgType.WNX_MSG.toNumber();

        Cursor unreadCur = sqlDb.rawQuery(unReadSql, null);
        int i = 0;
        if (unreadCur.moveToNext()) {
            i = unreadCur.getInt(0);
        }
        closeDbAndCursor(unreadCur);
        return i;
    }

    /**
     * 获取群助手所有未读数
     *
     * @return
     */
    public int getGroupUnreadCount() {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String unReadSql = " select sum(" + MessageRecordDao.COLUMN_MSG_UNREAD_COUNT + ") from " +
                MessageRecordDao.TABLE_NAME + " where " +
                MessageRecordDao.COLUMN_MSG_TYPE + " = " + MsgType.CHAT_CROUP.toNumber() + " and " +
                MessageRecordDao.COLUMN_MSG_GROUP_TYPE + " <> " + Type.GroupType.TEMP_GROUP + " AND " +
                MessageRecordDao.COLUMN_MSG_WARN_STATUS + " = " + MessageEntity.WarnStatus.WARN.toNumber() + " and " +
                MessageRecordDao.COLUMN_MSG_CONTENT_TYPE + " <>  " + ContentType.SYSTEM_WARN.toNumber();
        LogUtil.d(TAG, "wubaojie>>>getGroupUnreadCount: sql :" + unReadSql);
        Cursor unreadCur = sqlDb.rawQuery(unReadSql, null);
        int i = 0;
        if (unreadCur.moveToNext()) {
            i = unreadCur.getInt(0);
        }
        LogUtil.d(TAG, "wubaojie>>>getGroupUnreadCount: " + i);
        closeDbAndCursor(unreadCur);
        return i;
    }

    /**
     * 获取微农信列表根据机构分组
     */
    public ArrayList<WNXBean> getWnxList() {
        //根据机构分组 获取最新的提交数据，并将每组的未读数量算出
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ArrayList<WNXBean> beanList = new ArrayList<>();
        String sql = "select * " +
                "from " + NoticeDao.TABLE_NAME +
                " where " + NoticeDao.COLUMN_MSG_TYPE + " = " + MsgType.WNX_MSG.toNumber() +  /*" and " + NoticeDao
                .COLUMN_REMARK3 + " <> 1 " +*/
                " group by " + NoticeDao.COLUMN_MSG_SENDER_ID +
                " order by " + NoticeDao.COLUMN_MSG_SEND_TIME + " desc ";
        LogUtil.d(TAG, "wubaojie>>>" + "getWnxList: sql:" + sql);
        Cursor unreadCur = sqlDb.rawQuery(sql, null);
        while (unreadCur.moveToNext()) {
            WNXBean bean = buildNoticeDaoByCusor(unreadCur);
            Cursor countCur = sqlDb.rawQuery(" select count(*)  " +
                    "from " + NoticeDao.TABLE_NAME +
                    " where " + NoticeDao.COLUMN_MSG_SENDER_ID + " = '" + bean.msg_sender_id + "' and " + NoticeDao
                    .COLUMN_MSG_TYPE + " = " + MsgType.WNX_MSG.toNumber() +
                    " and " + NoticeDao.COLUMN_MSG_UNREAD_FLAG + " = 0", null);
            int count = 0;
            if (countCur.moveToFirst()) {
                count = countCur.getInt(0);
            }
            bean.unreadCount = count;
            bean.isCanSlide = true;
            beanList.add(bean);
            closeDbAndCursor(countCur);
        }
        closeDbAndCursor(unreadCur);
        LogUtil.d(beanList.toString());
        return beanList;

//        String sqlList = "select * from " + MessageRecordDao.TABLE_NAME;
//        Cursor listCursor = sqlDb.rawQuery(sqlList, null);
//        while (listCursor.moveToNext()) {
//            WNXBean bean = new WNXBean();
//            String sender_id = listCursor.getString(listCursor.getColumnIndex(MessageRecordDao
//                    .COLUMN_MSG_SENDER_ID));
//            Cursor beanCursor = sqlDb.rawQuery("select * " +
//                    "from " + NoticeDao.TABLE_NAME +
//                    " where " + NoticeDao.COLUMN_MSG_TYPE + " = " + MessageEntity.MsgType.WNX_MSG.toNumber() +
//                    " AND " + NoticeDao.COLUMN_MSG_SENDER_ID + " + '" + sender_id + "'" +
//                    " order by " + NoticeDao.COLUMN_MSG_SEND_TIME + " desc ", null);
//            if (beanCursor.moveToFirst()) {
//                bean = buildNoticeDaoByCusor(beanCursor);
//            }
//            bean.msg_sender_id = sender_id;
//            bean.msg_sender_name = listCursor.getString(listCursor.getColumnIndex(MessageRecordDao
//                    .COLUMN_MSG_SENDER_NAME));
//            Cursor countCur = sqlDb.rawQuery(" select count(*)  " +
//                    "from " + NoticeDao.TABLE_NAME +
//                    " where " + NoticeDao.COLUMN_MSG_SENDER_ID + " = '" + bean.msg_sender_id + "' and " + NoticeDao
//                    .COLUMN_MSG_TYPE + " = " + MessageEntity.MsgType.WNX_MSG.toNumber() +
//                    " and " + NoticeDao.COLUMN_MSG_UNREAD_FLAG + " = 0", null);
//
//            int count = 0;
//            if (countCur.moveToFirst()) {
//                count = countCur.getInt(0);
//            }
//            bean.unreadCount = count;
//            bean.isCanSlide = false;
//            beanList.add(bean);
//            closeDbAndCursor(countCur);
//            closeDbAndCursor(beanCursor);
//        }
//        closeDbAndCursor(listCursor);
//        LogUtil.d(beanList.toString());
//        return beanList;
    }

//    public ArrayList<MessageEntity> getWNXMessageList() {
//        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
//        ArrayList<MessageEntity> beanList = new ArrayList<>();
//        String sql = "select * " +
//                "from " + MessageRecordDao.TABLE_NAME +
//                " where " + MessageRecordDao.COLUMN_MSG_TYPE + " = " +
//                MessageEntity.MsgType.WNX_MSG.toNumber();
//        LogUtil.d(TAG, "wubaojie>>>" + "getWnxList: sql:" + sql);
//        Cursor wnxMessage = sqlDb.rawQuery(sql, null);
//        while (unreadCur.moveToNext()) {
//            MessageEntity bean = buildWNXMessage(wnxMessage);
//
//            bean.isCanSlide = true;
//            beanList.add(bean);
//            closeDbAndCursor(countCur);
//        }
//        return beanList;
//    }
//
//    private MessageEntity buildWNXMessage(Cursor cursor) {
//        MessageEntity bean = new MessageEntity();
//        bean.inserttime = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_TIME_STAMP));
//        bean.msg_sender_name = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_SENDER_NAME));
//        bean.msg_sender_id = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_SENDER_ID));
//        bean.msg_content = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_CONTENT));
//        bean.msg_logo = cursor.getString(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_LOGO));
//        bean.msg_type = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_TYPE));
//
//        bean.msg_unread_count = cursor.getInt(cursor.getColumnIndex(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT));
//        return null;
//    }

    /**
     * 得到某个机构的所有 微农信 分页
     *
     * @param senderid
     * @param pageIndex
     * @return
     */
    public ArrayList<WNXBean> getWnxListBySenderId(String senderid, int pageIndex) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ArrayList<WNXBean> beanList = new ArrayList<>();
        String querySql =
                "SELECT * FROM " +
                        "(SELECT * FROM " + NoticeDao.TABLE_NAME +
                        "  WHERE " + NoticeDao.COLUMN_MSG_TYPE + " = '" + MsgType.WNX_MSG.toNumber() +
                        "' AND " + NoticeDao.COLUMN_MSG_SENDER_ID + " = '" + senderid + "'" +
                        " AND " + NoticeDao.COLUMN_REMARK3 + " <> 1 " +
                        " ORDER BY " + NoticeDao.COLUMN_MSG_SEND_TIME + " DESC  " +
                        " LIMIT " + PageUtil.PAGE_SIZE + " OFFSET " + pageIndex * PageUtil.PAGE_SIZE + ")" +
                        " ORDER BY " + NoticeDao.COLUMN_MSG_SEND_TIME + " ASC ";
        LogUtil.d(TAG, " querySql " + querySql);
        Cursor wnxCur = sqlDb.rawQuery(querySql, null);
        while (wnxCur.moveToNext()) {
            WNXBean bean = buildNoticeDaoByCusor(wnxCur);
            if (!TextUtils.isEmpty(bean.content)) {
                beanList.add(bean);
            }
        }
        closeDbAndCursor(wnxCur);
        LogUtil.d(beanList.toString());
        return beanList;
    }

    /**
     * 修改某个机构的所有未读状态为已读
     *
     * @param senderId
     */
    public void updateWnxOrgReadStatus(String senderId) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues updateCv = new ContentValues();
        updateCv.put(NoticeDao.COLUMN_MSG_UNREAD_FLAG, 1);
        int result = sqlDb.update(NoticeDao.TABLE_NAME, updateCv,
                NoticeDao.COLUMN_MSG_SENDER_ID + " = ? and  " + NoticeDao.COLUMN_MSG_TYPE + " = ?", new
                        String[]{senderId, MsgType.WNX_MSG.toNumber() + ""});
        LogUtil.d("更改机构所有记录未读状态 条数为result>>" + result);
    }

    /**
     * 根据插入时间更新某条公告推送的未读状态
     *
     * @param inserttime
     */
    public void updateNoticceReadStatus(String inserttime) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues updateCv = new ContentValues();
        updateCv.put(NoticeDao.COLUMN_MSG_UNREAD_FLAG, 1);
        int result = sqlDb.update(NoticeDao.TABLE_NAME, updateCv, NoticeDao.COLUMN_TIME_STAMP + " = ?", new
                String[]{inserttime});
        LogUtil.d("更改公告录未读状态 条数为result>>" + result);
    }


    public void updateNoticeRecordReadStatus(String inserttime, int msg_type) {
        Log.d(TAG, "updateNoticeRecordReadStatus() called with: inserttime = [" + inserttime + "], msg_type = [" +
                msg_type + "]");
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues updateCv = new ContentValues();
        updateCv.put(NoticeDao.COLUMN_MSG_UNREAD_FLAG, 1);
        int reulst = sqlDb.update(NoticeDao.TABLE_NAME, updateCv, NoticeDao.COLUMN_TIME_STAMP + " = ?", new
                String[]{inserttime});
        LogUtil.d("更改公告录未读状态 条数为result>>" + reulst);
        if (msg_type == MsgType.NOTICE.toNumber()) {
            //公告的话要减去列表的数量
            boolean isExsit = isExsitMotice(sqlDb, msg_type);
            LogUtil.d(isExsit + "");
            int count = otherMap.get(msg_type);
            LogUtil.d("旧的未读数量》" + count);
            count -= reulst;
            LogUtil.d("新的未读数量》" + count);
            //更新相应记录
            ContentValues updateValue = new ContentValues();
            if (count >= 0) {
                LogUtil.d("大于0");
                updateValue.put(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT, count);
            } else {
                LogUtil.d("小于0");
                updateValue.put(MessageRecordDao.COLUMN_MSG_UNREAD_COUNT, 0);
            }
            try {
                int result = sqlDb.update(MessageRecordDao.TABLE_NAME, updateValue, MessageRecordDao.COLUMN_MSG_TYPE
                        + " = ? ", new String[]{msg_type + ""});
                LogUtil.d("更新消息列表未读数量>>" + result + " count >" + count);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 是否存在该条通知公告或者微农信
     */
    public boolean isNoticeWnxExist(String msgId) {
        boolean isExist = false;
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String isExistSql = "select * from " + NoticeDao.TABLE_NAME + " where  " + NoticeDao.COLUMN_MSG_ID + " = '" +
                msgId + "'";

        Cursor isExistCur = sqlDb.rawQuery(isExistSql, null);
        if (isExistCur.moveToNext()) {
            isExist = true;
        }
        try {
            isExistCur.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isExist;
    }

    public synchronized long insertNewFriend(NewFriendBean bean) {
        if (TextUtils.isEmpty(bean.user_id)) {
            LogUtil.d("userId不能为空");
            return 0;
        }
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String queryUser = "select * from " + MyNewFriendDao.TABLE_NAME + " where " + MyNewFriendDao.COLUMN_USER_ID +
                " = '" + bean.user_id + "'";
        Cursor queryCursor = sqlDb.rawQuery(queryUser, null);
        if (queryCursor.moveToFirst()) {
            ContentValues userValues = new ContentValues();
            String isAdd = queryCursor.getString(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_IS_ADD));
            if (!TextUtils.isEmpty(isAdd)) { //之前同意过申请了,又能够发来申请,表示把好友关系删除了,需要重建联系
                insertOrUpdateUnReadCount(); //新的申请,需要增加提醒数字
            } //否则为相同的重复提醒,不增加提醒数字
            userValues.put(MyNewFriendDao.COLUMN_REQ_DESC, bean.req_desc);
            userValues.put(MyNewFriendDao.COLUMN_ADD_STATUS, bean.add_status);
            userValues.put(MyNewFriendDao.COLUMN_FRIEND_LOGO, bean.user_logo);
            userValues.put(MyNewFriendDao.COLUMN_IS_ADD, ""); //每次重新申请需要把已添加状态清空
            userValues.put(MyNewFriendDao.COLUMN_INSERT_TIME, System.currentTimeMillis());
            int updateResult = sqlDb.update(MyNewFriendDao.TABLE_NAME, userValues, MyNewFriendDao.COLUMN_USER_ID
                    + "= ? ", new String[]{bean.user_id});
            LogUtil.d(TAG, "好友申请updateResult >>" + updateResult);
            return updateResult;
        } else {
            ContentValues userValues = new ContentValues();
            userValues.put(MyNewFriendDao.COLUMN_INSERT_TIME, System.currentTimeMillis());
            userValues.put(MyNewFriendDao.COLUMN_ADD_STATUS, bean.add_status);
            userValues.put(MyNewFriendDao.COLUMN_USER_ID, bean.user_id);
            userValues.put(MyNewFriendDao.COLUMN_USER_LOGO, bean.user_logo);
            userValues.put(MyNewFriendDao.COLUMN_USER_NAME, bean.user_name);
            userValues.put(MyNewFriendDao.COLUMN_FRIEND_ID, bean.friend_id);
            userValues.put(MyNewFriendDao.COLUMN_FRIEND_NAME, bean.friend_name);
            userValues.put(MyNewFriendDao.COLUMN_FRIEND_LOGO, bean.friend_logo);
            userValues.put(MyNewFriendDao.COLUMN_REQ_DESC, bean.req_desc);
            long insertResult = sqlDb.insert(MyNewFriendDao.TABLE_NAME, null, userValues);
            LogUtil.d(TAG, "好友申请insertResult >>" + insertResult);
            insertOrUpdateUnReadCount();
            return insertResult;
        }
    }

    public synchronized void insertOrUpdateUnReadCount() {
        String user_id = MyInfoUtil.getMyUserid(BaseApplication.mInstance);
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String queryUser = "select * from " + MyNewFriendDao.TABLE_NAME + " where " + MyNewFriendDao.COLUMN_USER_ID +
                " = '" + user_id + "'";
        Cursor queryCursor = sqlDb.rawQuery(queryUser, null);
        if (queryCursor.moveToFirst()) {
            ContentValues userValues = new ContentValues();
            int unReadCount = queryCursor.getInt(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_UNREAD_COUNT));
            userValues.put(MyNewFriendDao.COLUMN_UNREAD_COUNT, (unReadCount + 1));
            int updateResult = sqlDb.update(MyNewFriendDao.TABLE_NAME, userValues, MyNewFriendDao.COLUMN_USER_ID
                    + "= ? ", new String[]{user_id});
            LogUtil.d(TAG, "更新未读信息updateResult >>" + updateResult);
        } else {
            ContentValues userValues = new ContentValues();
            userValues.put(MyNewFriendDao.COLUMN_USER_ID, user_id);
            userValues.put(MyNewFriendDao.COLUMN_UNREAD_COUNT, 1);
            long insertResult = sqlDb.insert(MyNewFriendDao.TABLE_NAME, null, userValues);
            LogUtil.d(TAG, "插入未读信息insertResult >>" + insertResult);
        }
    }

    public synchronized void clearUnReadCount() {
        String user_id = MyInfoUtil.getMyUserid(BaseApplication.mInstance);
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues userValues = new ContentValues();
        userValues.put(MyNewFriendDao.COLUMN_UNREAD_COUNT, 0);
        sqlDb.update(MyNewFriendDao.TABLE_NAME, userValues, MyNewFriendDao.COLUMN_USER_ID + "= ? ", new
                String[]{user_id});
    }

    public synchronized int getUnReadCount() {
        int unReadCount = 0;
        String user_id = MyInfoUtil.getMyUserid(BaseApplication.mInstance);
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String queryUser = "select * from " + MyNewFriendDao.TABLE_NAME + " where " + MyNewFriendDao.COLUMN_USER_ID +
                " = '" + user_id + "'";
        LogUtil.d(TAG, "wubaojie>>>getUnReadCount: " + queryUser);
        Cursor queryCursor = sqlDb.rawQuery(queryUser, null);
        if (queryCursor.moveToFirst()) {
            unReadCount = queryCursor.getInt(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_UNREAD_COUNT));
        }
        LogUtil.d(TAG, "wubaojie>>>getUnReadCount: " + unReadCount);
        return unReadCount;
    }

    public synchronized ArrayList<NewFriendBean> getNewFriendList() {
        String user_id = MyInfoUtil.getMyUserid(BaseApplication.mInstance);
        ArrayList<NewFriendBean> dataList = new ArrayList<>();
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String queryUser = "select * from " + MyNewFriendDao.TABLE_NAME + " WHERE " +
                MyNewFriendDao.COLUMN_USER_ID + " <> '" + user_id + "' ORDER BY " +
                MyNewFriendDao.COLUMN_INSERT_TIME + " DESC";
        Cursor queryCursor = sqlDb.rawQuery(queryUser, null);
        while (queryCursor.moveToNext()) {
            NewFriendBean bean = new NewFriendBean();
            bean.add_status = queryCursor.getInt(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_ADD_STATUS));
            bean.friend_id = queryCursor.getString(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_FRIEND_ID));
            bean.friend_name = queryCursor.getString(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_FRIEND_NAME));
            bean.friend_logo = queryCursor.getString(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_FRIEND_LOGO));
            bean.user_id = queryCursor.getString(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_USER_ID));
            bean.user_name = queryCursor.getString(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_USER_NAME));
            bean.user_logo = queryCursor.getString(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_USER_LOGO));
            bean.req_desc = queryCursor.getString(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_REQ_DESC));
            bean.is_add = queryCursor.getString(queryCursor.getColumnIndex(MyNewFriendDao.COLUMN_IS_ADD));
            dataList.add(bean);
        }
        return dataList;
    }

    public synchronized int deleteOneFriendApplication(NewFriendBean bean) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        String where = MyNewFriendDao.COLUMN_USER_ID + "=?";
        int deleteResult = sqlDb.delete(MyNewFriendDao.TABLE_NAME, where, new String[]{bean.user_id});
        LogUtil.d(TAG, String.format("删除%s的好友申请id为%s，结果为%d", bean.user_name, bean.user_id, deleteResult));
        return deleteResult;
    }

    public synchronized int updateFriendStatus(NewFriendBean bean) {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        ContentValues userValues = new ContentValues();
        userValues.put(MyNewFriendDao.COLUMN_ADD_STATUS, bean.add_status);
        //是否已读,加为好友后更新的状态,用于判断该条申请是否还有效
        userValues.put(MyNewFriendDao.COLUMN_IS_ADD, bean.add_status + "");
        int updateResult = sqlDb.update(MyNewFriendDao.TABLE_NAME, userValues, MyNewFriendDao.COLUMN_USER_ID
                + "= ? ", new String[]{bean.user_id});
        LogUtil.d(TAG, "同意好友申请updateResult >>" + updateResult);
        return updateResult;
    }

    public boolean cleanWNXDB() {
        SQLiteDatabase sqlDb = dbHelper.getWritableDatabase();
        int delete = sqlDb.delete(ChatFileDao.TABLE_NAME, null, null);
        int delete1 = sqlDb.delete(ChatRecordDao.TABLE_NAME, null, null);
        int delete2 = sqlDb.delete(MessageRecordDao.TABLE_NAME, null, null);
        int delete3 = sqlDb.delete(NoticeDao.TABLE_NAME, null, null);
        int delete4 = sqlDb.delete(OrgAllUserDao.TABLE_NAME, null, null);
        int delete5 = sqlDb.delete(PreferencesDb.TABLE_NAME, null, null);
        int delete6 = sqlDb.delete(MyNewFriendDao.TABLE_NAME, null, null);
//        sqlDb.execSQL("DELETE FROM " + ChatFileDao.TABLE_NAME);
//        sqlDb.execSQL("DELETE FROM " + ChatRecordDao.TABLE_NAME);
//        sqlDb.execSQL("DELETE FROM " + MessageRecordDao.TABLE_NAME);
//        sqlDb.execSQL("DELETE FROM " + NoticeDao.TABLE_NAME);
//        sqlDb.execSQL("DELETE FROM " + OrgAllUserDao.TABLE_NAME);
//        sqlDb.execSQL("DELETE FROM " + PreferencesDb.TABLE_NAME);
//        sqlDb.execSQL("DELETE FROM " + MyNewFriendDao.TABLE_NAME);
        return true;
    }

}
